Mantra how-to guide

Understanding access conditions and prerequests

Mantra access conditions and prerequests are useful 'hooks' to reduce coding size of your views, posts, gets and blocks handlres

17-Apr-2022
A  A  A 

Usually, in any requests interaction with a Mantra application (in the form of a view or block to render or posts and gets calls to manage), there are two aspects in common in most of projects:

  • Accessibility (is this call request allowed?, ie.)

  • The need to get some data needed for the handler (over with data entity is this request interested in?, ie.)

One of the Mantra main features (and development paradigm) is based in that the coding size of any of those handlers, should be as minimal as posible.

Why?

Because by doing so, the understanding and maintenability of that handler will be easier (less expensive in the long run). If you focus in this kind of facts within your project, you'll get a more competitive software product cause you'll have to develop less lines of codes and the maintenability effort will be lower.

That's why in Mantra there exists two assets to allow this: access conditions and prerequests.

Access conditions (or AC) are intended to check any kind of accessibility to the handler (credentials, if current user logged in, status of the system and the like).

For its part, prerequests are inteneded to calculate some type of information for the handler.

If in the handler you need to code those two common aspects (accessibility and query any data needed), then the lines of code of the handler will be higher and the reusability of the project much lower.

Let's see it in a real example:

any_prerequest: ["articles.getarticleidfromurl", "articles.checkarticleexists"],
any_accesscondition: ["system.islogged"],
any: async (req,res) => {
    const Mantra = res.MantraAPI;
    const articleEntity = Mantra.GetRequestData( "articleentity" );

    // ... render the view
},

This code snipped is extracted from a component called "articles", and is part of its view handlers, so that this handler is called when pointing to "http://yoursite/articles/[article id]".

First of all, when that route is requested, Mantra runs those two prerequests: one to extract the id of the article (second parameter in the url), and the second to check if that article exists.

If all it's ok, the second prerequests adds the article entity to "articleentity" request data (to be get later in the handler with Mantra.GetRequestData() method).

After prerequests is called and returns true, then "system.islogged" access condition checks if the current user of the site is logged in. If not, then the view requests is rejected and redirect to landing page or other view.

By doing so, the code if the view handler in charge of redering the view is minimal.

For last, if you split some specific functionality of your project in this way, the reusability will be higher.