# Mantra API Reference ## Considrerations about Mantra API object In a Mantra project, any interaction between the framework and within the components, is performed using an single instance object of the class MantraAPI, usually named as Mantra in handlers. One interaction = one instace of that object. This API object is created by Mantra by each *interaction* with your project, like: * In any request for a view, get or post routes. * In an event handler. * In middlewares handlers. * In rendering blocks. * When running access conditions and prerequests. * etc. This is, when any component handler of any kind is called by Mantra Framework, a Mantra API object is created by the framework so that the handler doesn't need to create it. This is extremely important in Mantra Framework because, mainly, of performance: Mantra API object is heavy to create and load with initial values, and that's the reason why Mantra uses only one instance the this object in any *interaction*, and that's why API calls or DAL calls between components, should send this instance as well. This is how prerequests, for instance, can add data for the view handlers calling AddRequestData() method and share common data for the next handler call. Anyway, and despite it is not recommended (depending on the case), you can get a new instance of Mantra API object with: ```js const Mantra = global.Mantra.MantraAPIFactory(); ``` Mantra is a high performance framework because in any request or *interaction* between components, a Mantra API object is shared. ## Mantra API methods reference Mantra API object is the heart of the framework, all it's represented by its methods. To develop Mantra applications, you need to master this object. * [Mantra.AddCss](#mantra.addcss) * [Mantra.AddDataValue](#mantra.adddatavalue) * [Mantra.AddJs](#Mantra.addjs) * [Mantra.AddRenderValue](#mantra.addrendervalue) * [Mantra.AddRenderValues](#mantra.addrendervalues) * [Mantra.AddRequestData](#mantra.addrequestdata) * [Mantra.Config](#mantra.config) * [Mantra.ComponentEntities](#mantra.componententities) * [Mantra.ComponentEntitiesFromSchema](#mantra.componententitiesfromschema) * [Mantra.DynamicComponentEntities](#mantra.dynamiccomponententities) * [Mantra.EmitEvent](#mantra.emitevent) * [Mantra.EndGetRequest](#mantra.endgetrequest) * [Mantra.ExistsBlock](#mantra.existsblock) * [Mantra.ExistsComponentApi](#mantra.existscomponentapi) * [Mantra.ExistsComponentByName](#mantra.existscomponentbyname) * [Mantra.ExistsView](#mantra.existsview) * [Mantra.ExtractResource](#mantra.extractresource) * [Mantra.GetAppName](#mantra.getappname) * [Mantra.GetAssetsLocations](#mantra.getassetslocations) * [Mantra.GetComponentConfig](#mantra.getcomponentconfig) * [Mantra.GetComponentDbConfig](#mantra.getcomponentdbconfig) * [Mantra.GetComponentDependencies](#mantra.getcomponentdependencies)] * [Mantra.GetComponentLocation](#mantra.getcomponentlocation) * [Mantra.GetComponentVersion](#mantra.getcomponentversion) * [Mantra.GetDataValues](#mantra.getdatavalues) * [Mantra.GetExtendsByType](#mantra.getextendsbytype) * [Mantra.GetProjectDirectory](#mantra.getprojectdirectory) * [Mantra.GetGlobalVar](#mantra.getglobalvar) * [Mantra.GetHooksByName](#mantra.gethooksbyname) * [Mantra.GetInjection](#mantra.getinjection) * [Mantra.GetInstanceId](#mantra.getinstanceid) * [Mantra.GetRenderValues](#mantra.getrendervalues) * [Mantra.GetRequestData](#mantra.getrequestdata) * [Mantra.GetRequestPath](#mantra.getrequestpath) * [Mantra.GetRequest](#mantra.getrequest) * [Mantra.GetResponse](#mantra.getresponse) * [Mantra.GetSchemaByVersion](#mantra.getschemabyversion) * [Mantra.GetView](#mantra.getview) * [Mantra.GetViewHtml](#mantra.getviewhtml) * [Mantra.GlobalConfig](#mantra.globalconfig) * [Mantra.InstallDynamicSchema](#mantra.installdynamicschema) * [Mantra.InstallSchema](#mantra.installschema) * [Mantra.Invoke](#mantra.invoke) * [Mantra.IsGet](#mantra.isget) * [Mantra.IsIndex](#mantra.isindex) * [Mantra.IsPost](#mantra.ispost) * [Mantra.IsServiceActive](#mantra.isserviceactive) * [Mantra.LoadSchema](#mantra.loadschema) * [Mantra.LogInfo](#mantra.loginfo) * [Mantra.LogWarning](#mantra.logwarning) * [Mantra.LogError](#mantra.logerror) * [Mantra.PostRaw](#mantra.postraw) * [Mantra.PostUnauthorizedCode](#mantra.postunauthorizedcode) * [Mantra.Redirect](#mantra.redirect) * [Mantra.RedirectToRoot](#mantra.redirecttoroot) * [Mantra.RenameSchemaEntities](#mantra.renameschemaentities) * [Mantra.Render](#mantra.render) * [Mantra.RenderContent](#mantra.rendercontent) * [Mantra.RenderFullViewHtml](#mantra.renderfullviewhtml) * [Mantra.RenderHtml](#mantra.renderhtml) * [Mantra.RenderLandingPage](#mantra.renderlandingpage) * [Mantra.RenderRawView](#mantra.renderrawview) * [Mantra.RenderRawViewContentHtml](#mantra.renderrawviewcontenthtml) * [Mantra.RenderRoot](#mantra.renderroot) * [Mantra.RenderTemplate](#mantra.rendertemplate) * [Mantra.RenderTemplateFromFile](#mantra.rendertemplatefromfile) * [Mantra.RenderView](#mantra.renderview) * [Mantra.RenderViewHtml](#mantra.renderviewhtml) * [Mantra.SendError](#mantra.senderror) * [Mantra.SendFailure](#mantra.sendfailure) * [Mantra.SendFile](#mantra.sendfile) * [Mantra.SendHtml](#mantra.sendhtml) * [Mantra.SendStatus](#mantra.sendstatus) * [Mantra.SendSuccess](#mantra.sendsuccess) * [Mantra.UninstallSchema](#mantra.uninstallschema) * [Mantra.UpdateSchema](#mantra.updateschema) * [Mantra.UpdateSchemaWithCurrentEntities](#mantra.updateschemawithcurrententities) # MantraAPI methods definitions ## Mantra.AddCss ```js AddCss( resource ) ``` Adds to the current request a css file placed at "css" folder. Like AddJs, the "resource" parameter indicates which css file to include following one of these two formats options: * "componentname.filename": Mantra will look for a css file inside "/componentname/ui/js", in the folder of the component indicated in the first part of the parameter. * "frontend.pathtofile": in this case, "frontend" is a special key string indicating to Mantra that the file should be found in the UI assets of the current application. All css files added with AddCss() in the same request, will be rendered at "mantra-css-files" Mustache tag indicated in html root document. See [Adapting Root Html Document to Mantra](/docs/adapting-root-html-document-to-mantra.md) for more infor about Mantra Mustache tags. Also, the parameter can be an array with a number of js resources to include. You can also define the css files to include in on specific view indicating "_css": property in its definition. Some examples: ```js Mantra.AddCss( "cookieswarning.alertckstyle" ); // Will include /cookieswarning/ui/css/alertckstyle.css file. Mantra.AddCss( "frontend.assets/css/alertckstyle.css"; // Will include the file /assets/css/alertckstyle.css that should be at the UI folder of the current application Mantra.AddCss( ["alerts.showalertstyle", "seo.settitlestyle"] ); // Will include those two css files. ``` ## Mantra.AddDataValue ```js AddDataValue( key, value ) ``` Adds data to be used by javascript browser client with Mantra.data property Params: * key: * value: All keys indicated with AddDataValue(), will be inserted in Mantra.data object. Given AddDataValue( 'title', 'Lord of the Rings' ), then, javascript browser client, will have Mantra.data.title property with value 'Lord of the Rings'. ## Mantra.AddJs ```js AddJs( resource ) ``` Adds to the current request a javascript file placed at "js" folder. The "resource" parameter indicates which js file to include following one of these two formats options: * "componentname.filename": Mantra will look for a js file inside "/componentname/ui/js", in the folder of the component indicated in the first part of the parameter. * "frontend.pathtofile": in this case, "frontend" is a special key string indicating to Mantra that the file should be found in the UI assets of the current application. All js files added with AddJs() in the same request, will be rendered at "mantra-js-files" Mustache tag indicated in html root document. See [Adapting Root Html Document to Mantra](/22-docs/adapting-root-html-document-to-mantra.md) for more infor about Mantra Mustache tags. Also, the parameter can be an array with a number of js resources to include. You can also define the js files to include in on specific view indicating "_js": property in its definition. Some examples: ```js Mantra.AddJs( "cookieswarning.alertck" ); // Will include /cookieswarning/ui/js/alertck.js file. Mantra.AddJs( "frontend.assets/js/popupmessages.js"; // Will include the file /assets/js/popupmessages.js that should be at the UI folder of the current application Mantra.AddJs( ["alerts.showalert", "seo.settitle"] ); // Will include those two js files. ``` Remember: files to add in the next rendering process (js and css) are not ordered in anyway. ## Mantra.AddRenderValue ```js AddRenderValue( key, value ) ``` Adds data to be used in rendering using render engine template in views, blocks, etc. Params: * key: * value: For example, by running Mantra.AddRenderValue( "name", "Mantra Microkernel Framework" ), when rendering any html piece of code with Mustache syntax like: ```html

{{name}}

``` , will be rendered as: ```html

Mantra Microkernel Framework

``` ## Mantra.AddRenderValues ```js AddRenderValues( values ) ``` Adds data to be used in rendering using render engine template in views, blocks, etc. Params: * values: ## Mantra.AddRequestData ```js AddRequestData( key, value ) ``` Adds data to be used in same request. Params: * key: * value: 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](/docs/15-component-prerequests.md) hooks. ## Mantra.ComponentEntities ```js 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](https://github.com/mantrajsframework/redentities) with the API of this library. ## Mantra.ComponentEntitiesFromSchema ```js ComponentEntitiesFromSchema( componentName, schema ) ``` Creates a new RedEntities instance intialized with a specific schema for the given component. Refer to [RedEntities](https://github.com/mantrajsframework/redentities) with the API of this library. Params: * componentName: * schema: *Remember*: component name is needed to load the database configuration for the component in "Entities" property of mantraconfig.json file. ## Mantra.Config ```js Config( componentProperty ) ``` Returns a component property componentProperty is in the format "component name"."component property". This method is equivalent to use "config" property shortcut: ```js Mantra.config.componentname.property ``` Se [Components Configuration](/docs/18-component-configuration.md) for more details about component configurations. ## Mantra.DynamicComponentEntities ```js 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](https://github.com/mantrajsframework/redentities) with the API of this library. Params: * componentName: * schema: *Remember*: component name is needed to load the database configuration for the component in "Entities" property of [mantraconfig.json](/docs/36-mantraconfig-json-file.md) file. ## Mantra.EmitEvent ```js async EmitEvent( eventName, eventData ) ``` Emits an event to be managed by components events subscribers. Params: * eventName: * eventData: See [Component Events](/docs/19-component-events-subscription.md) for more information about Mantra events. ## Mantra.EndGetRequest ```js async EndGetRequest( data ) ``` Ends current request sending back the data indicated as parameter. This is equivalent to call [Response.end(data)](https://expressjs.com/en/api.html#res.end) method of Express object. ## Mantra.ExistsBlock ```js ExistsBlock( componentName, blockName) ``` Returns true if a block exists. Params: * componentName: * blockName: ## Mantra.ExistsComponentApi ```js ExistsComponentApi( api ) ``` Returns true if there is registered an api path, given in the format of "component name.api name". Remember: files to add in the next rendering process (js and css) are not ordered in anyway. ## Mantra.ExistsComponentByName ```js ExistsComponentByName( componentName ) ``` Returns true if a component with the name indicated as parameter exists. ## Mantra.ExistsView ```js async ExistsView( view ) ``` Returns true if a view exists. Param: * view: ## Mantra.ExtractResource ```js 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: ```json { exists: , isFrontendResource: , isComponentResource: , fileType: , isMimeType: } ``` ## Mantra.GetAppName ```js GetAppName() ``` Returns a string with the name of the current running application. ## Mantra.GetAssetsLocations ```js GetAssetsLocations() ``` Returns the [Assets Locations](/docs/35-assetslocations-reference.md) instance with methods to locate assets within the project. ## Mantra.GetComponentConfig ```js GetComponentConfig( componentName ) ``` Returns the full config json object for a component given its name. See [Component Config](/docs/18-component-configuration.md) for more info about components configuration. ## Mantra.GetComponentDbConfig ```js GetComponentDbConfig( componentName ) ``` Returns the json object with the database access properties indicated for the component, according to property "Entities" in [mantraconfig.json](/docs/36-mantraconfig-json-file.md) 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. ## Mantra.GetComponentDependencies ```js GetComponentDependencies( componentName ) ``` Returns in an array the name of the components that a component depends on. ## Mantra.GetComponentLocation ```js GetComponentLocation(componentName) ``` Returns de full path to the location of a component given its name. Exception launched if component doesn't exist. ## Mantra.GetComponentVersion ```js GetComponentVersion(componentName) ``` Returns the version of a component. This version is de "version" property of mantra.json file for the component. ## Mantra.GetExtendsByType ```js GetExtendsByType( type ) ``` Returns an array with all extends for the given type. With [Extends](/docs/16-component-extend.md), any component can define its own types of *hooks* for multiple purposes. * Mantra.GetProjectDirectory ```js GetProjectDirectory() ``` Returns the absolute root directory of the current project. ## Mantra.GetDataValues ```js 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(). ## Mantra.GetGlobalVar ```js 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: ```js let globalSiteName = Mantra.GetGlobalVar( "global-sitename" ) ``` ## Mantra.GetHooksByName ```js 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" ## Mantra.GetInjection ```js GetInjection( inyectionKey ) ``` Returns the value of an injection as indicated in Injections section of mantraconfig.json file. ## Mantra.GetInstanceId ```js GetInstanceId() ``` Returns the current instance id of the application running. For more details about instance id, see [Instance Id](/docs/32-instanceid.md) document. ## Mantra.GetRenderValues ```js 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). ## Mantra.GetRequestData ```js GetRequestData( key ) ``` Gets especific data added previously with AddRequestData() to be used in the same request. ## Mantra.GetRequestPath ```js GetRequestPath() ``` Returns a string with the current requested path. Sends the ["path" property](http://expressjs.com/en/4x/api.html#req.path) of Request Express object. ## Mantra.GetResponse ```js GetResponse() ``` Returns the [Response Express](http://expressjs.com/en/4x/api.html#res) object of the current request. ## Mantra.GetRequest ```js GetRequest() ``` Returns the [Request Express](http://expressjs.com/en/4x/api.html#req) object of the current request. ## Mantra.GetSchemaByVersion ```js async GetSchemaByVersion( componentName, version ) ``` Loads a component schema. Params: * componentName: * version: 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. ## Mantra.GetView ```js async GetView( view ) ``` Returns the html content of a view. Param: * view: ## Mantra.GetViewHtml ```js async GetViewHtml( pathToView ) ``` Returns the html content for a view. Return the view html content "as it is", without the rendering process. Param: * pathToView: .html> ## Mantra.GlobalConfig ```js GlobalConfig( "propertyname" ) ``` Returns the value of property indicated in GlobalConfig section of mantraconfig.json file. ## Mantra.InstallDynamicSchema ```js 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: * jsonSchema: * removesIfExists: ## Mantra.InstallSchema ```js async InstallSchema( componentName ) ``` This method installs the schema of a component. This schema (or database model), should be placed at //model/.schema.json. The method loads that file and uses [RedEntities](https://github.com/mantrajsframework/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](/docs/20-component-entity-model.md). Usually, this method is called at onInstall() method in the [component definition](/docs/05-mantra-component-definition.md). InstallSchema() looks for the schema that match de component version. If no exists, then the default one will be used. For instance: ```js await Mantra.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. ## Mantra.IsServiceActive ```js 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](/docs/25-mantra-services.md) for more information. ## Mantra.IsGet ```js IsGet() ``` Returns a boolean indicating if current request is a HTTP GET request. ## Mantra.IsIndex ```js IsIndex() ``` Returns a boolean indicating if current request path is the root ("/"). ## Mantra.Invoke ```js async Invoke( apiToCall, data = {} ) ``` Invokes an API method defined by a component. Params: * apiToCall: * data: Returns the value returned by the API method. This method is equivalent to use "api" property shorcut: ```js Mantra.api.componentname.apiname ``` See [Component APIs](/docs/09-component-apis.md) for more info about API registration. ## Mantra.IsPost ```js IsPost() ``` Returns a boolean indicating if current request is a HTTP POST request. ## Mantra.LoadSchema ```js async LoadSchema( schema ) ``` Load the json for a schema according to the Param: * schema: . >. Mantra expects to locate the schema at "//model/.schema.json" file. Returns the json object with the schema loaded. ## Mantra.LogError ```js async LogError( description, data = "", key = "", counter = 0 ) ``` Adds an error message to log. Params: * description: * data: * key: * counter: ## Mantra.LogInfo ```js async LogInfo( description, data = "", key = "", counter = 0 ) ``` Adds an info message to log. Params: * description: * data: * key: * counter: ## Mantra.LogWarning ```js async LogWarning( description, data = "", key = "", counter = 0 ) ``` Adds a warning message to log. Params: * description: * data: * key: * counter: ## Mantra.PostRaw ```js PostRaw( data ) ``` Ends the current post request sending the json object indicated as parameter. ## Mantra.PostUnauthorizedCode ```js PostUnauthorizedCode() ``` Ends the current post request with HTTP status code 401 (Unauthorized). More about HTTP status code [here](#https://developer.mozilla.org/en-US/docs/Web/HTTP/status). ## Mantra.Redirect ```js async Redirect( path ) ``` Redirects current request to the path indicated as parameter. Equivalent to use [Response.redirect()](http://expressjs.com/en/4x/api.html#res.redirect) method of Express. ## Mantra.RedirectToRoot ```js async RedirectToRoot() ``` Redirects current request to the root ("/"). Equivalent to use [Response.redirect("/")](http://expressjs.com/en/4x/api.html#res.redirect) method of Express. ## Mantra.RenameSchemaEntities ```js async RenameSchemaEntities( componentName, schema, sufix ) ``` Renames the entities of the schema adding to the a sufix. Params: * componentName: * schema: * sufix: ## Mantra.Render ```js async Render( html ) ``` Renders the html document indicated as parameter. Al data to render within the document, should be indicated previously with Mantra.AddRenderValue o Mantra.AddRenderValues. If the document contains blocks, then they are rendered as well. Retursn the document fully rendered. ## Mantra.RenderContent ```js 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: * htmlContainerFile: ## Mantra.RenderFullViewHtml ```js async RenderFullViewHtml( componentName, viewName, htmlContainerFile ) ``` Render a view of a component and returns its full html content (container included). Params: * componentName: * viewName: . * htmlContainerFile: ## Mantra.RenderHtml ```js RenderHtml( templateHtml, data ) ``` Renders the text html document with data. Params: * templateHtml: * data: Returns the html document rendered. ## Mantra.RenderLandingPage ```js async RenderLandingPage() ``` Renders default "index.html" document. ## Mantra.RenderRawView ```js async RenderRawView( viewHtml, htmlContainer ) ``` Renders the html content of a view in the root container html document. Params: * viewHtml: * htmlContainer: ## Mantra.RenderRawViewContentHtml ```js 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: * htmlContainerFile: ## Mantra.RenderRoot ```js 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: ```js await Mantra.RenderRoot("/404.html"); ``` ## Mantra.RenderTemplate ```js async RenderTemplate( templatefile, data ) ``` Renders a template file with data. The template file is indicated as "/