Global

Members

process: Process

Information about current executable. Accessible via global variable process

console: Console

Put something to log with log levels depending on method

_: lodash

Instance of lodash library. Follow this link to see documentation on the official site.

__filename: String

The filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

__dirname: String

Full path to the folder that the currently executing script resides in.

module: RequiredModule

A reference to the current module

TubLoadContentBody

Properties:
Name Type Description
Default
Yes
No

TubAttrDataType: Number readonly

Entity attributes data type
Properties:
Name Type Description
Unknown Number
String Number
Int Number
BigInt Number
Float Number
Currency Number
Boolean Number
DateTime Number
Text Number
ID Number
Entity Number
Document Number
Many Number
TimeLog Number
Enum Number
BLOB Number
Date Number

TubCacheType: Number readonly

Entity cache type
Properties:
Name Type Description
None Number
SessionEntity Number
Entity Number
Session Number

TubSQLDialect: Number readonly

Supported SQL dialects
Properties:
Name Type Description
AnsiSQL Number
Oracle Number
Oracle9 Number
Oracle10 Number
Oracle11 Number
MSSQL Number
MSSQL2008 Number
MSSQL2012 Number
SQLite3 Number
PostgreSQL Number
Firebird Number

TubEntityDataSourceType: Number readonly

Entity dataSource types
Properties:
Name Type Description
Normal Number
External Number
System Number
Virtual Number

TubSQLExpressionType: Number readonly

SQL expression types
Properties:
Name Type Description
Field Number
Expression Number

Methods

require(moduleName) → *

Load a module. Acts like a Node JS require, with 4 difference:

  • Core modules list is: ["fs", "util", "path", "assert", "module", "console" and "events"] - this modules always loaded from bin\modules folder
  • In case of moduleName is RELATIVE (not start from ./ ../ or X:\ where X is drive letter) lookup order is:
    • currentModulePath + \modules
    • currentModulePath + \node_modules
    • bin\modules
    • process.cwd()
  • in case UnityBase run in production (!process.isDebug) and package.json contain main_min entry it value will be used as a module entry point
    Placing minimized js into main_min help to prevent memory overflow;
  • require know about UnityBase models. In server thread context, in case moduleName start from models/ModelName require search for module inside ModelName.path folder:

     require('models/UBS/public/UBReport');

    will search in domain config (ubConfig.json) path for UBS model and perform request relative to this folder, i.e. load D:\projects\UnityBase\models\UBS\public\UBReport.js in my case.

    In case you need to debug from there module is loaded set OS Environment variable >SET NODE_DEBUG=modules and restart server - require will put to debug log all information about how module are loaded. Do not do this on production, of course :)

Arguments:
  1. moduleName (String)

atob()

The same as window.atob in browser. Warning! slow implementation.

btoa()

The same as window.btoa in browser. Warning! slow implementation.

toLog(log, formatopt, valueopt)

Put something to server log (in case of GUI server - duplicate message to log panel)

console.debug('Value we got is', 12);
Arguments:
  1. log (Number|String|Object)  if {Number} - this is log level and function wait additional args
  2. [format] (Object|String|Number)  place % inside format string to indicate where to put value
  3. [value] (Object|String|Number)
Deprecated:
  • Deprecated since 1.8. Use console.[log|debug|warn|error] instead

removeCommentsFromJSON(JSONString)String

Remove comments from JSON string (actually replace all comment content with ' ')
Arguments:
  1. JSONString (String)  String to remove comments from

forceDirectories(pathToDir)boolean

ForceDirectories ensures that all the directories in a specific path exist. Any portion that does not already exist will be created. Function result indicates success of the operation. The function can fail if the current user does not have sufficient file access rights to create directories in the given path.
Arguments:
  1. pathToDir (String)

removeDir(pathToDir)boolean

Deletes an existing empty directory. Call removeDir to remove the directory specified by the Dir parameter. The return value is True if a new directory was successfully deleted, False if an error occurred. The directory must be emptied before it can be successfully deleted When working with symlinks, there are some special cases to consider because of how symlinks are implemented on different platforms. On Windows, RemoveDir can only delete a symbolic link from a directory, regardless if the directory link is broken or not
Arguments:
  1. pathToDir (String)

createGuid()string

Create GUID

sleep(ms) protected

For test purpose only. Suspend thread for ms millisecond
Arguments:
  1. ms (Number)  millisecond to sleep

worker(paramsObj)Number

Run script in separate thread (experimental). Returns thread ID.

Thread creates in suspended state. When we post new worker message thread resumes and call onmessage handler. When thread terminates and Terminate handler assigned worker thread call onterminate handler. In handlers you can use 2 methods:

postMessage(message) for posting messages from worker thread. You can get this message by function getMessage of worker object

terminate() for terminating current worker thread

Arguments:
  1. paramsObj (Object)  parameters object
    Properties
    1. onmessage (String|function)  Message handler. Has 1 parameter - message. Before call
    2. onterminate (String|function)  Terminate handler. Has no parameters

postWorkerMessage(threadID, message)

Post message to worker thread. Worker call onmessage handler with parameter message
Arguments:
  1. threadID (Number)
  2. message (String)

getWorkerMessage(threadID)String|undefuned

Get message from worker thread. If worker thread didn't post any message then return undefined
Arguments:
  1. threadID (Number)

terminateWorkerThread(threadID)

Terminate worker thread.
Arguments:
  1. threadID (Number)

gc() protected

Perform Garbage collection for current scripting context. Use it if you know WHAT you do!

ncrc32(initialValue, data)number

Native CRC32 implementation. Much (x100) faster compared to JS implemenattion
Arguments:
  1. initialValue (Number)  Must be 0 in case no initial value
  2. data (String|ArrayBuffer|ArrayBufferView)  Data to calculate CRC32. In case of string will be transformed to UFT8 before calculation

nsha256(data)String

Native SHA256 implementation. Much (x10) faster compared to JS implementation
Arguments:
  1. data (String|ArrayBuffer|ArrayBufferView)  Data to calculate SHA256. In case of string will be transformed to UFT8 before calculation

module:cmd/initDB(options)

If DBA already create a database for you set both dropDatabase & createDatabase to false
Arguments:
  1. options (Object)
    Properties
    1. [clientIdentifier=3] (Number)  Identifier of the client. Must be between 2 and 8999. Number 1 is for UnityBase developer, 3 for test. Numbers > 100 is for real installations
    2. [dropDatabase=false] (Boolean)  Drop a database/schema first
    3. [createDatabase=false] (Boolean)  Create a new database/schema.
    4. [dba] (String)  A DBA name. Used in case createDatabase=true
    5. [dbaPwd] (String)  A DBA password. Used in case createDatabase=true

Events

exit

Fires for the {process} instance when application stop working for each Working Thread

 process.on('exit', function(){
     console.log('thread is terminated');
 });

domainIsLoaded

Fires for a App just after all domain entites (all *.meta) is in server memory, and all server-side js is evaluated. On this stage you can subscruibe/add cross-model handles.

       App.once('domainIsLoaded', function(){
           var
                domain = App.domain,
                ettCnt = domain.count,
                entityMeta, entityObj;

           // all models are evaluated into memory, so we can enumerate enitties here
           for (var i = 0; i < ettCnt; i++) {
                entityMeta = domain.items[i];
                if (entityMeta.attributes.byName('mi_fedUnit')) {
                    entityObj = global[entityMeta.name];
                    entityObj.on('insert:before', fedBeforeInsert); // add before insert handler
                }
           }
});

login

Fires just after user successfully logged-in but before auth response is written to client. Inside models initialization script you can subscribe to this event and add some data to Session.uData. No parameter is passed to this event handler. Example below add someCustomProperty to Session.uData and this value is accessible on client via $App.connection.userData(someCustomProperty):

 Session.on('login', function(){
     var uData = Session.uData;
     uData.someCustomProperty = 'Hello!';
 });

See real life example inside \models\ORG\org.js.

registration

Fires in case auth endpoint is called with registration=1 parameter and authentication schema support "registration" feature (currently only CERT schema support this feature).

Inside event handler server-side Session object is in INCONSISTENT state and you must not use it!! Only parameter (stringified object), passed to event is valid user-relative information.

Each AUTH schema can pass his own object as a event parameter, but all schema add authType. Below is a sample code for CERT schema:

 Session.on('registration', function(registrationParams){

 }

loginFailed

Fires in case auth endpoint is called with authentication schema UB and userName is founded in database, but password is incorrect.

If wrong passord is entered more than UBA.passwordPolicy.maxInvalidAttempts(from ubs_settings) times user will be locked

2 parameters passes to this event userID(Number) and isUserLocked(Boolean)

 Session.on('loginFailed', function(userID, isLocked){
     if (isLocked)
         console.log('User with id ', userID, 'entered wrong password and locked');
     else
         console.log('User with id ', userID, 'entered wrong password');
 })

securityViolation

Fires in case of any security violation:

  • user is blocked or not exists (in uba_user)
  • user provide wrong credential (password, domain, encripted secret key, certificate etc)
  • for 2-factor auth schemas - too many sessions in pending state (max is 128)
  • access to endpoint "%" deny for user (endpoint name not present in uba_role.allowedAppMethods for eny user roles)
  • password for user is expired (see ubs_settings UBA.passwordPolicy.maxDurationDays key)
  • entity method access deny by ELS (see rules in uba_els)

1 parameter passes to this event reason: string

 Session.on('securityViolation', function(reason){
     console.log('Security violation for user with ID', Session.userID, 'from', Session.callerIP, 'reason', reason);
 })