@unitybase/ub

JavaScript Style Guide

This model is a main entry point for a UnityBase server application.

Application

In term of UnityBase application is defined by:

  • configuration (ubConfig.json by default): file what describe settings for http server, logging, authorization methods, Domain, etc. See server config json schema for full description
  • package.json - npm/yarn configuration used to give information to package manager that allows it to identify the project as well as handle the project's dependencies

Inside package.json main field is the primary entry point to UnityBase application. In most case entry point file content is

const UB = require('@unitybase/ub')
UB.start()

Application initialization

UB.start method of @unitybase/ub package will:

  • parse application config passed as -cfg command line parameter to ub and put parsed content to App.serverConfig
  • create HTTP server and configure it using parameters from httpServer config section

and perform steps below for every HTTP thread:

  • read and validate all *.meta files from folders, defined in application.domain.models
  • for each model from application.domain.models folders (except ones marked as _public_only_) load a model (see below)
  • register build-in UnityBase endpoints
  • emit App.domainIsLoaded event

Model

Server-side

Model is a commonJS module with logically grouped set of entities + server side code + client-side code. In the application config (ubConfig.json) application.domain.models section contains an array of models, required by application.

Model is loaded in server thread memory(in order they defined in application.domain.models config section) in three steps:

  • entity namespaces (global objects) are created for all *.meta files from this model
  • require is called for all *.js files paired with *.meta
  • require is called for model entry point defined in package.json placed in the model folder

To simplify a ubConfig model package.json can contains config.ubmodel section what describe the model name and (optionally) "isPublic": true` for "browser-only" model

"config": {
    "ubmodel": {
      "name": "UBS"
    }
  },

for "browser-only" model:

  "config": {
    "ubmodel": {
      "name": "adminui-pub",
      "isPublic": true
    }
  },

For such models only path to model should be added to the application.domain.models section of ubConfig.json:

    "application": {
        ...
        "domain": {
            "models": [
                ...
                {
                    "path": "./node_modules/@unitybase/ubs"
                },

Client-side (adminUI)

Model can contains a "browser-side" part. In this case model package.json should contains browser section what point to the model initialization script for browser

  • In case model is a published module (placed in the node_modules folder) path should be relative to the package.json:

    "browser": "./public/initModel.js"
  • or for dev/prod scripts

    "browser": {
     "dev": "./public/devEntryPoint.js"
     "prod": "./public/dist/modelBundle.js"
    }
  • In case model is in models folder p[ath must be absolute

    "browser": "/clientRequire/models/TST/initModel.js",

Endpoints

UnityBase comes with simple one-level routing. App.registerEndpoint method will add a handlers functions for a first level of routing:

/**
 * Write a custom request body to file FIXTURES/req and echo file back to client
 * @param {THTTPRequest} req
 * @param {THTTPResponse} resp
 */
function echoToFile(req, resp) {
   var fs = require('fs');
   fs.writeFileSync(FIXTURES + 'req', req.read('bin'));
   resp.statusCode = 200;
   resp.writeEnd(fs.readFileSync(FIXTURES + 'req', {encoding: 'bin'}));
}
App.registerEndpoint('echoToFile', echoToFile);

More deep routing can be implemented inside the endpoint handler, as we did inside build-in UnityBase endpoints

JSON schemas

@unitybase/ub/public/schemas folder contains JSON schemas for server config, entity meta file and scheduler config. It's a good idea to configure your IDE for JSON schema support. See for example WebStorm IDE configuratuion manual

Classes

DataStore
ub_blobHistory_ns

Submodules

endpoints    i18n    modelLoader    onlyOfficeEndpoints    ubErrors    web-sockets   

Members

App: App static

Application instance

ESecurityException: ESecurityException static

Server-side Security exception. Throwing of such exception will trigger Session.securityViolation event

i18nExtend static

Merge localizationObject to UB.i18n
Example
const UB = require('@unitybase/ub')
UB.i18nExtend({
 "en": {yourMessage: "yourTranslationToEng", ...},
 "uk": {yourMessage: "yourTranslationToUk", ...},
  ....
})
// if logged in user language is `en` will output "yourTranslationToEng"
console.log(UB.i18n(yourMessage))
// will output "yourTranslationToUk"
console.log(UB.i18n(yourMessage, 'uk'))

isServer static readonly

If we are in UnityBase server scripting (both -f or server thread) this property is true, if in browser - undefined or false. Use it for check execution context in scripts, shared between client & server. To check we are in server thread use process.isServer.

loadLegacyModules static

For UB < 4.2 compatibility - require all non - entity js in specified folder add it's subfolder (one level depth), exclude modules and node_modules subfolder's. From 'public' subfolder only cs*.js are required. To be called in model index.js as such: const modelLoader = require('@unitybase/ub).modelLoader

For new models we recommend to require non-entity modules manually

Session: Session static

Information about the logged in user

UBAbort: UBAbort static

Server-side Abort exception. To be used in server-side logic in case of HANDLED exception. This errors logged using "Error" log level to prevent unnecessary EXC log entries.

ub_blobHistory: ub_blobHistory_ns inner constant

File BLOB history. Store historical data for all file based BLOB stores

Methods

i18n(msg, langopt) static

Translate message specified language using data, prepared by UB.i18nExtend To add model-depended values in your model use UB.i18nExtend
Arguments:
  1. msg (String)  Message to translate
  2. [lang] (String)  language to translate to. if not passed - current user session language used, or default application language if not logged in

Repository(entityName, cfgopt, connectionopt)ServerRepository static

Create new instance of ServerRepository
Arguments:
  1. entityName (String)
  2. [cfg] (Object)
  3. [connection] (SyncConnection)  Pass in case of remote UnityBase server connection.

ns(namespacePath)Object inner

Creates namespaces to be used for scoping variables and classes so that they are not global.

UB.ns('DOC.Report');
DOC.Report.myReport = function() { ... };
Arguments:
  1. namespacePath (String)
Deprecated:
  • Try to avoid namespaces - instead create a modules and use require()

start() inner

Initialize UnityBase application:

  • create namespaces (global objects) for all *.meta files from domain
  • require all packages specified in config application.domain.models
  • emit App.domainIsLoaded event
  • register build-in UnityBase endpoints

JavaScript Style Guide

This model is a main entry point for a UnityBase server application.

Application

In term of UnityBase application is defined by:

  • configuration (ubConfig.json by default): file what describe settings for http server, logging, authorization methods, Domain, etc. See server config json schema for full description
  • package.json - npm/yarn configuration used to give information to package manager that allows it to identify the project as well as handle the project's dependencies

Inside package.json main field is the primary entry point to UnityBase application. In most case entry point file content is

const UB = require('@unitybase/ub')
UB.start()

Application initialization

UB.start method of @unitybase/ub package will:

  • parse application config passed as -cfg command line parameter to ub and put parsed content to App.serverConfig
  • create HTTP server and configure it using parameters from httpServer config section

and perform steps below for every HTTP thread:

  • read and validate all *.meta files from folders, defined in application.domain.models
  • for each model from application.domain.models folders (except ones marked as _public_only_) load a model (see below)
  • register build-in UnityBase endpoints
  • emit App.domainIsLoaded event

Model

Server-side

Model is a commonJS module with logically grouped set of entities + server side code + client-side code. In the application config (ubConfig.json) application.domain.models section contains an array of models, required by application.

Model is loaded in server thread memory(in order they defined in application.domain.models config section) in three steps:

  • entity namespaces (global objects) are created for all *.meta files from this model
  • require is called for all *.js files paired with *.meta
  • require is called for model entry point defined in package.json placed in the model folder

To simplify a ubConfig model package.json can contains config.ubmodel section what describe the model name and (optionally) "isPublic": true` for "browser-only" model

"config": {
    "ubmodel": {
      "name": "UBS"
    }
  },

for "browser-only" model:

  "config": {
    "ubmodel": {
      "name": "adminui-pub",
      "isPublic": true
    }
  },

For such models only path to model should be added to the application.domain.models section of ubConfig.json:

    "application": {
        ...
        "domain": {
            "models": [
                ...
                {
                    "path": "./node_modules/@unitybase/ubs"
                },

Client-side (adminUI)

Model can contains a "browser-side" part. In this case model package.json should contains browser section what point to the model initialization script for browser

  • In case model is a published module (placed in the node_modules folder) path should be relative to the package.json:

    "browser": "./public/initModel.js"
  • or for dev/prod scripts

    "browser": {
     "dev": "./public/devEntryPoint.js"
     "prod": "./public/dist/modelBundle.js"
    }
  • In case model is in models folder p[ath must be absolute

    "browser": "/clientRequire/models/TST/initModel.js",

Endpoints

UnityBase comes with simple one-level routing. App.registerEndpoint method will add a handlers functions for a first level of routing:

/**
 * Write a custom request body to file FIXTURES/req and echo file back to client
 * @param {THTTPRequest} req
 * @param {THTTPResponse} resp
 */
function echoToFile(req, resp) {
   var fs = require('fs');
   fs.writeFileSync(FIXTURES + 'req', req.read('bin'));
   resp.statusCode = 200;
   resp.writeEnd(fs.readFileSync(FIXTURES + 'req', {encoding: 'bin'}));
}
App.registerEndpoint('echoToFile', echoToFile);

More deep routing can be implemented inside the endpoint handler, as we did inside build-in UnityBase endpoints

JSON schemas

@unitybase/ub/public/schemas folder contains JSON schemas for server config, entity meta file and scheduler config. It's a good idea to configure your IDE for JSON schema support. See for example WebStorm IDE configuratuion manual

Classes

DataStore
ub_blobHistory_ns

Submodules

endpoints    i18n    modelLoader    onlyOfficeEndpoints    ubErrors    web-sockets   

Members

App: App static

Application instance

ESecurityException: ESecurityException static

Server-side Security exception. Throwing of such exception will trigger Session.securityViolation event

i18nExtend static

Merge localizationObject to UB.i18n
Example
const UB = require('@unitybase/ub')
UB.i18nExtend({
 "en": {yourMessage: "yourTranslationToEng", ...},
 "uk": {yourMessage: "yourTranslationToUk", ...},
  ....
})
// if logged in user language is `en` will output "yourTranslationToEng"
console.log(UB.i18n(yourMessage))
// will output "yourTranslationToUk"
console.log(UB.i18n(yourMessage, 'uk'))

isServer static readonly

If we are in UnityBase server scripting (both -f or server thread) this property is true, if in browser - undefined or false. Use it for check execution context in scripts, shared between client & server. To check we are in server thread use process.isServer.

loadLegacyModules static

For UB < 4.2 compatibility - require all non - entity js in specified folder add it's subfolder (one level depth), exclude modules and node_modules subfolder's. From 'public' subfolder only cs*.js are required. To be called in model index.js as such: const modelLoader = require('@unitybase/ub).modelLoader

For new models we recommend to require non-entity modules manually

Session: Session static

Information about the logged in user

UBAbort: UBAbort static

Server-side Abort exception. To be used in server-side logic in case of HANDLED exception. This errors logged using "Error" log level to prevent unnecessary EXC log entries.

ub_blobHistory: ub_blobHistory_ns inner constant

File BLOB history. Store historical data for all file based BLOB stores

Methods

i18n(msg, langopt) static

Translate message specified language using data, prepared by UB.i18nExtend To add model-depended values in your model use UB.i18nExtend
Arguments:
  1. msg (String)  Message to translate
  2. [lang] (String)  language to translate to. if not passed - current user session language used, or default application language if not logged in

Repository(entityName, cfgopt, connectionopt)ServerRepository static

Create new instance of ServerRepository
Arguments:
  1. entityName (String)
  2. [cfg] (Object)
  3. [connection] (SyncConnection)  Pass in case of remote UnityBase server connection.

ns(namespacePath)Object inner

Creates namespaces to be used for scoping variables and classes so that they are not global.

UB.ns('DOC.Report');
DOC.Report.myReport = function() { ... };
Arguments:
  1. namespacePath (String)
Deprecated:
  • Try to avoid namespaces - instead create a modules and use require()

start() inner

Initialize UnityBase application:

  • create namespaces (global objects) for all *.meta files from domain
  • require all packages specified in config application.domain.models
  • emit App.domainIsLoaded event
  • register build-in UnityBase endpoints