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:
process
Name | Type | Description |
---|---|---|
Default |
||
Yes |
||
No |
TubAttrDataType: Number readonly
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
Properties:
Name | Type | Description |
---|---|---|
None |
Number | |
SessionEntity |
Number | |
Entity |
Number | |
Session |
Number |
TubSQLDialect: Number readonly
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
Properties:
Name | Type | Description |
---|---|---|
Normal |
Number | |
External |
Number | |
System |
Number | |
Virtual |
Number |
TubSQLExpressionType: Number readonly
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:
-
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:
-
log
(Number|String|Object)
 if {Number} - this is log level and function wait additional args
-
[format]
(Object|String|Number)
 place % inside format string to indicate where to put value
-
[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:
-
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:
-
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:
-
pathToDir
(String)
createGuid() → string
Create GUID
sleep(ms)
protected
For test purpose only. Suspend thread for ms millisecond
Arguments:
-
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:
-
paramsObj
(Object)
 parameters object
Properties
postWorkerMessage(threadID, message)
Post message to worker thread. Worker call onmessage handler with parameter message
Arguments:
getWorkerMessage(threadID) → String|undefuned
Get message from worker thread. If worker thread didn't post any message then return undefined
Arguments:
-
threadID
(Number)
terminateWorkerThread(threadID)
Terminate worker thread.
Arguments:
-
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:
-
initialValue
(Number)
 Must be 0 in case no initial value
-
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:
-
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:
-
options
(Object)
Properties
-
[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
-
[dropDatabase=false]
(Boolean)
 Drop a database/schema first
-
[createDatabase=false]
(Boolean)
 Create a new database/schema.
-
[dba]
(String)
 A DBA name. Used in case createDatabase=true
-
[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);
})
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 frombin\modules
folder - In case of
moduleName
is RELATIVE (not start from./
../
orX:\
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 containmain_min
entry it value will be used as a module entry point
Placing minimized js intomain_min
help to prevent memory overflow; require
know about UnityBase models. In server thread context, in casemoduleName
start frommodels/ModelName
require search for module insideModelName.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. loadD:\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 :)
moduleName
(String)
Put something to server log (in case of GUI server - duplicate message to log panel)
console.debug('Value we got is', 12);
log
(Number|String|Object)
 if {Number} - this is log level and function wait additional args
[format]
(Object|String|Number)
 place % inside format string to indicate where to put value
[value]
(Object|String|Number)
- Deprecated since 1.8. Use console.[log|debug|warn|error] instead
JSONString
(String)
 String to remove comments from
pathToDir
(String)
pathToDir
(String)
ms
(Number)
 millisecond to sleep
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
paramsObj
(Object)
 parameters object
Properties
threadID
(Number)
threadID
(Number)
initialValue
(Number)
 Must be 0 in case no initial value
data
(String|ArrayBuffer|ArrayBufferView)
 Data to calculate CRC32. In case of string will be transformed to UFT8 before calculation
data
(String|ArrayBuffer|ArrayBufferView)
 Data to calculate SHA256. In case of string will be transformed to UFT8 before calculation
dropDatabase
& createDatabase
to false
options
(Object)
Properties
-
[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 -
[dropDatabase=false]
(Boolean)
 Drop a database/schema first -
[createDatabase=false]
(Boolean)
 Create a new database/schema. -
[dba]
(String)
 A DBA name. Used in casecreateDatabase=true
-
[dbaPwd]
(String)
 A DBA password. Used in casecreateDatabase=true
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
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);
})