Mantra API Reference

In a Mantra project, any interaction between the framework and within the components, is performed using an object of the class MantraAPI.

This API object is created con each request or in any other kind of a the component behaviour (like cron jobs, for instance).

Described below all MantraAPI methods.

MantraAPI methods definitions

MantraAPI.GetAppName

GetAppName()

Returns a string with the name of the current running application.

MantraAPI.GetAssetsLocations

GetAssetsLocations()

Returns the Assets Locations instance with methods to locate assets within the project.

MantraAPI.GetBaseUrl

GetBaseUrl()

Returns a string with the base url property indicated in "core" configuration module (property "core.baseurl").

MantraAPI.GetRequestPath

GetRequestPath()

Returns a string with the current requested path.

Sends the "path" property of Request Express object.

MantraAPI.GetHooksByName

GetHooksByName( hookName )

Returns an array of json objects with all hooks (like "view", "post", etc.) registered by all components in the system.

Each json object of the hook have the properties indicated when they were registered in the onStart() method of the component.

Available hooks are:

  • "accesscondition"
  • "api"
  • "block"
  • "command"
  • "componentextend"
  • "cron"
  • "event"
  • "get"
  • "middleware"
  • "post"
  • "prerequest"
  • "view"

MantraAPI.GetResponse

GetResponse()

Returns the Response Express object of the current request.

MantraAPI.GetRequest

GetRequest()

Returns the Request Express object of the current request.

MantraAPI.IsGet

IsGet()

Returns a boolean indicating if current request is a HTTP GET request.

MantraAPI.IsPost

IsPost()

Returns a boolean indicating if current request is a HTTP POST request.

MantraAPI.Redirect

async Redirect( path )

Redirects current request to the path indicated as parameter.

Equivalent to use Response.redirect() method of Express.

MantraAPI.RedirectToRoot

async RedirectToRoot()

Redirects current request to the root ("/").

Equivalent to use Response.redirect("/") method of Express.

MantraAPI.SendFile

async SendFile( fullPathToFile )

Send a file to the current request. The file should be located with its full path indicated in the parameter.

Equivalent to user Response.sendfile() method of Express.

MantraAPI.IsIndex

IsIndex()

Returns a boolean indicating if current request path is the root ("/").

MantraAPI.RenderRoot

async RenderRoot( htmlRootDocument )

Send as response the rendering of the full html document indicated as parameter.

The file to render should be placed under the frontend application folder.

As an example:

await MantraAPI.RenderRoot("/404.html");

MantraAPI.RenderViewHtml

async RenderViewHtml( componentName, viewName )

Renders a view and returns its full html content (container not included).

Params:

  • componentName: <name of the component>
  • viewName: <name of the view to render (no extension file needed)

As an example:

let viewHtml = await MantraAPI.RenderViewHtml( "books", "showfullbook" );

MantraAPI.RenderRawViewContentHtml

async RenderRawViewContentHtml( viewHtml, htmlContainerFile = 'index.html' ) {

Render the content of the html view indicated in viewHtml in the container indicated in htmlContainerFile and returns the resulting html content.

Params:

  • viewHtml: <html content to render in the container file>
  • htmlContainerFile: <container file name, default "index.html">

MantraAPI.GetGlobalVar

GetGlobalVar( globalVarKey )

Get the value of a global variable, included in section "GlobalTemplateVars" of mantraconfig.json file.

Returns '(unknown)' if the key entry doesn't exist.

As an example:

let globalSiteName = MantraAPI.GetGlobalVar( "global-sitename" )

MantraAPI.RenderContent

async RenderContent( htmlViewContent, htmlContainerFile )

This is the main method to render contents in mantra UI. Returns the rendering html document for the html view indicated in htmlViewConent.

Params:

  • htmlViewContent: <html to render with blocks, data values, etc>
  • htmlContainerFile: <optional, file of the container, like "index.html">

MantraAPI.RenderFullViewHtml

async RenderFullViewHtml( componentName, viewName, htmlContainerFile )

Render a view of a component and returns its full html content (container included).

Params:

  • componentName: <name of the component which defines the view>
  • viewName: <name of the view>.
  • htmlContainerFile: <html content of the container where render the view>

MantraAPI.RenderView

RenderView( view, htmlContainerFile )

This is the main method to be used in views function handlers to render component views. Renders a view and ends the get requests by sending its content.

Params:

  • view: <view to render in the format component.viewname>
  • htmlContainerFile: <optional, main container for the view, by default index.html>

As an example:

await RenderView( "books.showfullbookinfo" )

This sample sends back as response of a request the rendering of the view "showfullbookinfo" (expected to be located at /books/views/showfullbookinfo.html) within the default document root of "index.html".

MantraAPI.ExistsBlock

ExistsBlock( componentName, blockName)

Returns true if a block exists.

Params:

  • componentName: <component name>
  • blockName: <name of the block to check if exists>

MantraAPI.GetViewHtml

async GetViewHtml( pathToView )

Returns the html content for a view. Return the view html content "as it is", without the rendering process.

Param:

  • pathToView: <relative path to the file containing the view: /component/views/<viewname>.html>

MantraAPI.ExistsView

async ExistsView( view )

Returns true if a view exists.

Param:

  • view: <view in the form of "[component name].[view name]", like "users.showuser">

MantraAPI.SendHtml

async SendHtml( htmlContent )

Sends html content over response object of the current request.

Param:

  • htmlContent: <raw html content to send>

MantraAPI.GetView

async GetView( view )

Returns the html content of a view.

Param:

  • view: <view in the form of "[component name].[view name]", like "users.showuser">

MantraAPI.GetInstanceId

GetInstanceId()

Returns the current instance id of the application running.

For more details about instance id, see Instance Id document.

MantraAPI.RenderRawView

async RenderRawView( viewHtml, htmlContainer )

Renders the html content of a view in the root container html document.

Params:

  • viewHtml: <html content of the view>
  • htmlContainer: <root document container, optional, default "index.html">

MantraAPI.EndGetRequest

async EndGetRequest( data )

Ends current request sending back the data indicated as parameter.

This is equivalent to call Response.end(data) method of Express object.

MantraAPI.RenderLandingPage

async RenderLandingPage()

Renders default "index.html" document.

MantraAPI.RenderTemplateFromFile

async RenderTemplateFromFile( pathToTemplateFile, data )

Renders a template from its full location and data

Params:

  • pathToTemplate: <full path to template>
  • data: <json object with data to render within the template>

Returns the html document template rendered.

MantraAPI.RenderTemplate

async RenderTemplate( templatefile, data )

Renders a template file with data. The template file is indicated as "<component name>/<template file name>" (with no ".html" extension).

firstly looks for the template file at /<site location>/ui/templates/<component name>/<template file>.

If it doesn't exist in that location, then looks for the template file at /<component>/ui/templates/<template file>.

If data is an array, then template file is rendered by each element.

Params:

  • templateFile: <local path to template inside site templates location (set in config) or component templates folder, like "pager/basepager" (no need to add .html extension)>
  • data: <json object with data to render | array object with json data to render, in this case, the template is rendered by each array item>

MantraAPI.RenderHtml

RenderHtml( templateHtml, data )

Renders the text html document with data.

Params:

  • templateHtml: <html text document to render>
  • data: <json object with data to render>

Returns the html document rendered.

MantraAPI.Render

async Render( html )

Renders the html document indicated as parameter.

Al data to render within the document, should be indicated previously with MantraAPI.AddRenderValue o MantraAPI.AddRenderValues.

If the document contains blocks, then they are rendered as well.

Retursn the document fully rendered.

MantraAPI.GetComponentLocation

GetComponentLocation(componentName)

Returns de full path to the location of a component given its name.

Exception launched if component doesn't exist.

MantraAPI.GetComponentVersion

GetComponentVersion(componentName)

Returns the version of a component. This version is de "version" property of mantra.json file for the component.

MantraAPI.InstallSchema

async InstallSchema( componentName )

This method installs the schema of a component.

This schema (or database model), should be placed at /<compoponent name>/model/<component name>.schema.json.

The method loads that file and uses RedEntities to create the database.

The database type for the component should be indicated in "Entities" propery of mantraconfig.json.

See more información about Mantra entities management.

Usually, this method is called at onInstall() method in the component definition.

InstallSchema() looks for the schema that match de component version. If no exists, then the default one will be used.

For instance:

await MantraAPI.InstallSchema( "users" );

If users has "1.0.3" version (indicated at "version" property at its mantra.json file), then InstallSchema() will try to locate first the model "/users/model/users.1.0.3.schema.json". If it doesn't exist, then "/users/model/users.schema.json" will be used.

MantraAPI.InstallDynamicSchema

async InstallDynamicSchema( componentName, jsonSchema, removesIfExists = true )

Install a new schema given its json definition. This is one of the advanced features of Mantra.

Params:

  • componentName: <name of the component which install the schema. According to this name, gets the right db configuration>
  • jsonSchema: <json of the schema to install>
  • removesIfExists: <if true, and if entities already exists, then they are removed and resintalled. If false, if an entity exists, then it is not removed. Default true>

MantraAPI.UninstallSchema

async UninstallSchema( componentName, schema )

Removes current schema for the componente indicated as parameter.

Param:

  • componentName: <name of the component which schema will be removed>
  • schema: <optional, json object with the schema. If not included, Mantra will use the default component schema mode located at "/component/model" folder>

As with InstallSchema() method, the schema (or database model), should be placed at /<compoponent name>/model/<component name>.schema.json.

The method loads that file and uses RedEntities to uninstall (remove) the database.

The database type for the component should be indicated in "Entities" propery of mantraconfig.json.

See more información about Mantra entities management.

Usually, this method is called at onUninstall() method in the component definition.

UninstallSchema() looks for the schema that match de component version. If no exists, then the default one will be used.

MantraAPI.UpdateSchema

async UpdateSchema( componentName, currentVersion, versionToUpdate, updateEntityFnc )

Updates a new schema for component. This method is complex and involves changes in DB.

It should be called from an onUpdate() method of the component definition. onUpdate() is called by Mantra when running 'update' command and if it detects changes in "version" property of mantra.json file of the component.

$ mantrad update

As with any othe important updatet in any software system, it is Recommended to make database backup before calling this method.

Params:

  • componentName: <name of the component to update>
  • currentVersion: <current version of the component installed in system, as indicated in previous mantra.json>
  • versionToUpdate: <new version to update of the component, as indicated in current mantra.json>
  • updateEntityFnc: <optional callback function: async (entityName, entity, db) {}, to be called for each current entity instance for each entity in current db>

Basically, the update process performs this:

  1. Renames current entities with the sufix "_temporal"
  2. Creates the new version of the schema
  3. To load old data to be stored at new schema (and maybe with changes or conversion in the data entities), then calls to updateEntityFnc() calback by each entity in the old schema.
  4. Removes temporal entities renamed at step 1.

The callback function, is given, is called by each entity (row) in the database, and has this prototype:

async function(entityName, entity, newdb)

Where:

  • entityName: <name of the entity (table)>
  • entity: <data of the entity (row)>
  • newdb: <RedEntities instance with the new db created and where the data of the old one should be saved>

Remember: one of the Mantra main concepts to scacle applications is that entities should be small (one, two of three tables by each component as much), the entities should be defined with simple types and entities for each components should not store "very long" data sets.

If long data sets are needed, then third options should be used.

MantraAPI.LoadSchema

async LoadSchema( schema )

Load the json for a schema according to the

Param:

  • schema: <path to the schema in typical definition of component assets: <component name>.<schema name> >. Mantra expects to locate the schema at "/<component name>/model/<component name>.schema.json" file.

Returns the json object with the schema loaded.

MantraAPI.GetSchemaByVersion

async GetSchemaByVersion( componentName, version )

Loads a component schema.

Params:

  • componentName: <name of the component>
  • version: <optional, indicates the version of the schema>

Given the sample "GetSchemaByVersion( "users" ), then will return "/users/model/users.schema.json" json object file.

Given the sample "GetSchemaByVersion( "users", "1.2.0" ), then will return "/users/model/users.1.2.0.schema.json" json object file.

MantraAPI.RenameSchemaEntities

async RenameSchemaEntities( componentName, schema, sufix )

Renames the entities of the schema adding to the a sufix.

Params:

  • componentName: <name of the component>
  • schema: <json object with the schema>
  • sufix: <string with the sufix to rename the entities (table names>

MantraAPI.ComponentEntities

ComponentEntities( componentName )

Returns a RedEntities instance configured with the schema of the component. The instance is returned initialized with the model schema of the component.

Refer to RedEntities with the API of this library.

MantraAPI.ComponentEntitiesFromSchema

ComponentEntitiesFromSchema( componentName, schema )

Creates a new RedEntities instance intialized with a specific schema for the given component.

Refer to RedEntities with the API of this library.

Params:

  • componentName: <name of the component>
  • schema: <json schema object with the model>

Remember: component name is needed to load the database configuration for the component in "Entities" property of mantraconfig.json file.

MantraAPI.DynamicComponentEntities

DynamicComponentEntities( componentName, schema )

Returns a RedEntities instance initialized with a specific schema for the given component.

Because the creation of RedEntities object is quite heavy, this object is cached internally, unlike ComponentEntitiesFromSchema() method.

Refer to RedEntities with the API of this library.

Params:

  • componentName: <name of the component>
  • schema: <json schema object with the model>

Remember: component name is needed to load the database configuration for the component in "Entities" property of mantraconfig.json file.

MantraAPI.GetComponentDbConfig

GetComponentDbConfig( componentName )

Returns the json object with the database access properties indicated for the component, according to property "Entities" in mantraconfig.json file.

Remember this is one of the principles in a Mantra application: a component can use its own database instance.

If no specific configuration is provided, "default" will be returned.

MantraAPI.GetExtendsByType

GetExtendsByType( type )

Returns an array with all extends for the given type.

With Extends, any component can define its own types of hooks for multiple purposes.

MantraAPI.AddRenderValue

AddRenderValue( key, value )

Adds data to be used in rendering using render engine template in views, blocks, etc.

Params:

  • key: <key name of the variable to render>
  • value: <value for the key>

For example, by running MantraAPI.AddRenderValue( "name", "Mantra Microkernel Framework" ), when rendering any html piece of code with Mustache syntax like:

<p></p>

, will be rendered as:

<p>Mantra Microkernel Framework</p>

MantraAPI.AddRenderValues

AddRenderValues( values )

Adds data to be used in rendering using render engine template in views, blocks, etc.

Params:

  • values: <json object with keys the their values to render>

MantraAPI.AddDataValue

AddDataValue( key, value )

Adds data to be used by javascript browser client with MantraAPI.data property

Params:

  • key: <key for the property>
  • value: <value for the property>

All keys indicated with AddDataValue(), will be inserted in MantraAPI.data object.

Given AddDataValue( 'title', 'Lord of the Rings' ), then, javascript browser client, will have MantraAPI.data.title property with value 'Lord of the Rings'.

MantraAPI.GetDataValues

GetDataValues()

Returns a hash table with all data values indicated previously with call to AddDataValue(). The keys of the hash table are the keys indicated when calling AddDataValue().

MantraAPI.AddRequestData

AddRequestData( key, value )

Adds data to be used in same request.

Params:

  • key: <key for the property to be used during the request management>
  • value: <value for that key>

When Mantra manages a request (http get, post, etc.), multiple calls are performed (core middlewares, component middlewares, prerequests hooks if present, etc.). Any of those calls can enrich the request data adding info to it.

An example of this, is performed when a prequest hook checks the id of the entity included in the url, then that prerequest adds the entity with AddRequestData() so that the view handler can have it.

This decouples the code so that the view handler can be minimal.

Usually, request data is added in prerequest hooks.

MantraAPI.GetRequestData

GetRequestData( key )

Gets especific data added previously with AddRequestData() to be used in the same request.

MantraAPI.GetRenderValues

GetRenderValues()

Gets the hash table with all data values added previusly with AddRenderValue() or AddRenderValues() used to render with then rendering template engine (Mustache by default in current version).

MantraAPI.PostRaw

PostRaw( data )

Ends the current post request sending the json object indicated as parameter.

MantraAPI.PostUnauthorizedCode

PostUnauthorizedCode()

Ends the current post request with HTTP status code 401 (Unauthorized).

More about HTTP status code here.

MantraAPI.SendStatus

SendStatus(statusCode)

Ends the current request with the http status indicated as parameter.

More about HTTP status code here.

MantraAPI.SendError

SendError( message )

Ends the current request with HTTP status code status 500 (Internal Server Error)

More about HTTP status code here.

MantraAPI.PostSuccess

PostSuccess( dataPayload = {} )

Ends a request with a response indicating success and an optional payload.

Params:

  • dataPayload: <optional, data to be sent with the post response, optional>

The method will response a json object with the property "success" to true:

{ success: true, payload: dataPayload }

MantraAPI.PostFailed

PostFailed( message, dataPayload = {} )

Ends a request with a response indicating failure and an optional payload.

Params:

  • dataPayload: <optional, data to be sent with the post response, optional>

The method will response a json object with the property "success" to false:

{ success: false, payload: dataPayload }

MantraAPI.AddJs

AddJs( resource )

Adds to the current request a javascript file placed at "js" folder. The resource is indicated with "componentname.filename" format or an array of "componentname.filename" strings.

All js files added with AddJs() in the same request, will be rendered at "mantra-js-files" Mustache tag indicated in html root document.

By using AddJs(), compacting all js files involved in the same request can be done efficiently by Mantra and at run-time when enabling this feature in core properties.

See Adapting Root Html Document to Mantra for more infor about Mantra Mustache tags.

MantraAPI.AddCss

AddCss( resource )

Adds to the current request a css file placed at "css" folder. The resource is indicated with "componentname.filename" format or an array of "componentname.filename" strings.

All css files added with AddCss() in the same request, will be rendered at "mantra-css-files" Mustache tag indicated in html root document.

By using AddCss(), compacting all css files involved in the same request can be done efficiently by Mantra and at run-time when enabling this feature in core properties.

See Adapting Root Html Document to Mantra for more infor about Mantra Mustache tags.

MantraAPI.ExistsComponentApi

ExistsComponentApi( api )

Returns true if there is registered an api path, given in the format of "component name.api name".

MantraAPI.ExistsComponentByName

ExistsComponentByName( componentName )

Returns true if a component with the name indicated as parameter exists.

MantraAPI.Invoke

async Invoke( apiToCall, data = {} )

Invokes an API method defined by a component.

Params:

  • apiToCall: <method of the api to call: component.apiname>
  • data: <data to pass to the api method, optional>

Returns the value returned by the API method.

This method is equivalent to use "api" property shorcut:

MantraAPI.api.componentname.apiname

See Component APIs for more info about API registration.

MantraAPI.ExistsComponentExtend

MantraAPI.GetComponentExtend

MantraAPI.GetComponentConfig

GetComponentConfig( componentName )

Returns the full config json object for a component given its name.

See Component Config for more info about components configuration.

MantraAPI.IsServiceActive

IsServiceActive(service)

Returns true if the service indicated as parameter is active in current running application.

Available Mantra services are 'view','post','get','middleware' and 'cron'.

See Mantra Services for more information.

MantraAPI.Config

Config( componentProperty )

Returns a component property componentProperty is in the format "component name"."component property".

This method is equivalent to use "config" property shortcut:

MantraAPI.config.componentname.property

Se Components Configuration for more details about component configurations.

MantraAPI.EmitEvent

async EmitEvent( eventName, eventData )

Emits an event to be managed by components events subscribers.

Params:

  • eventName: <name of the event>
  • eventData: <data for the event, optional>

See Component Events for more information about Mantra events.

MantraAPI.LogInfo

async LogInfo( description, data = "", key = "", counter = 0 )

Adds an info message to log.

Params:

  • description: <description of the log>
  • data: <string data to add to the log trace, optional>
  • key: <string key associated with the log trace, optional>
  • counter: <counter for the log trace in the case multiple logs at the same time, optional>

MantraAPI.LogWarning

async LogWarning( description, data = "", key = "", counter = 0 )

Adds a warning message to log.

Params:

  • description: <description of the log>
  • data: <string data to add to the log trace, optional>
  • key: <string key associated with the log trace, optional>
  • counter: <counter for the log trace in the case multiple logs at the same time, optional>

MantraAPI.LogError

async LogError( description, data = "", key = "", counter = 0 )

Adds an error message to log.

Params:

  • description: <description of the log>
  • data: <string data to add to the log trace, optional>
  • key: <string key associated with the log trace, optional>
  • counter: <counter for the log trace in the case multiple logs at the same time, optional>

MantraAPI.ConsoleQuestion

async ConsoleQuestion( question )

Useful for Component Commands, awaits to a console question to by typed by the user. The response is returned as string.

MantraAPI.ExtractResource

async ExtractResource( resource )

Given a resource path, returns a json object indicating information about if it is a frontend or a component resource.

The json returned is like this:

{
    exists: <true if the resource exists>,
    isFrontendResource: <true if it is a front end resource>,
    isComponentResource: <true if it is a component resource>,
    fileType: <extension of the resource>,
    isMimeType: <true if it is a MIME type>
}