new SyncConnection(options)
Synchronous server-side connection to the UnityBase instance. To be used only inside UnityBase. For nodeJS & browser use asynchronous UBConnection class from @unitybase/ub-pub package.
The most used method is SyncConnection.query - a authorized request to ubql endpoint.
const SyncConnection = require('@unitybase/base').SyncConnection
let conn = new SyncConnection({URL: 'http://localhost:888'})
conn.onRequestAuthParams = function(){ return {authSchema: 'UB', login: 'admin', password: 'admin'} }
var domain = conn.getDomainInfo();
if (domain.has('my_entity')){
..
}
Arguments:
-
options(Object) Connection parameters. See http.request for details
Members
appConfig: Object
AdminUI settings
appName: String
readonly
Name of UnityBase application
authMethods: Array.<string>
readonly
Possible server authentication method
authNeed: Boolean
readonly
Is UnityBase server require authorization
clientRequest: ClientRequest
protected
readonly
Internal instance of HTTP client
encryptContent: Boolean
readonly
Is server require content encryption
onRequestAuthParams: function
Callback for resolving user credential.
Take a SyncConnection as a parameter, must return authorization parameters object:
{authSchema: authType, login: login, password: password, [apiKey: ]}
For a internal usage (requests from a locahost or other systems, etc.) and in case authShema == 'UB' it is possible to pass a
apiKey instead of a password. apiKey is actually a uba_user.uPasswordHashHexa content
queryMethod: string
Endpoint name for query (runList before 1.12, ubql after 1.12)
serverCertificate: Boolean
readonly
base64 encoded server certificate used for cryptographic operation
servicePath: String
readonly
Root path to all application-level method
sessionKeyLifeTime: Number
readonly
Lifetime (in second) of session encryption
_domain: UBDomain
inner
Methods
get(endpoint, URLParamsopt) → ArrayBuffer|Object|String
Perform get request to endpoint with optional URLParams.
Arguments:
-
endpoint (String)
-
[URLParams] (*)
getAppInfo() → Object
Return information about how application is configured as returned by getAppInfo endpoint
getDocument(params, optionsopt) → Promise
Retrieve content of document type attribute field from server. Usage samples:
//Retrieve content of document as string using GET
let frmContent = conn.getDocument({
entity:'ubm_form',
attribute: 'formDef',
ID: 100000232003
})
console.log(typeof frmContent)
//The same, but using POST for bypass cache
let frmContent = conn.getDocument({
entity:'ubm_form',
attribute: 'formDef',
ID: 100000232003
}, {
bypassCache: true
})
console.log(typeof frmContent) // string
//Retrieve content of document as ArrayBuffer and bypass cache
let frmContent = conn.getDocument({
entity:'ubm_form',
attribute: 'formDef',
ID: 100000232003
}, {
bypassCache: true, resultIsBinary: true
})
console.log('Result is', typeof frmContent, 'of length' , frmContent.byteLength, 'bytes'); //output: Result is object of length 2741 bytes
Arguments:
-
params (Object)
Properties
-
entity (String)  Code of entity to retrieve from
-
attribute (String)  document type attribute code
-
id (Number)  Instance ID
-
[forceMime] (String)  If passed and server support transformation from source MIME type to forceMime server perform transformation and return documenRt representation in the passed MIME
-
[revision] (Number)  Optional revision of the documnet (if supported by server-side store configuration). Default is current revision.
-
[fileName] (String)  ????
-
[isDirty=false] (Boolean)  Optional ability to retrieve document in dirty state
-
[store] (String)  ????
-
[options] (Object)  Additional request options
Properties
getDomainInfo(isExtendedopt) → UBDomain
Retrieve application domain information.
Arguments:
-
[isExtended=false] (Boolean)  For member of admin group cen return a addinitonal domain information, such as mappings, connection details, indexes
insert(ubq) → *
Execute insert method by add method: 'insert' to ubq query (if req.method not already set)
If ubq.fieldList contain only ID return inserted ID, else return array of attribute values passed to fieldList.
If no field list passed at all - return response.resultData (null usually).
var testRole = conn.insert({
entity: 'uba_role',
fieldList: ['ID', 'mi_modifyDate'],
execParams: {
name: 'testRole1',
allowedAppMethods: 'runList'
}
});
console.log(testRole); //[3000000000200,"2014-10-21T11:56:37Z"]
var testRoleID = conn.insert({
entity: 'uba_role',
fieldList: ['ID'],
execParams: {
name: 'testRole1',
allowedAppMethods: 'runList'
}
});
console.log(testRoleID); //3000000000200
Arguments:
-
ubq (ubRequest)
isAuthorized() → boolean
Check is current connection already perform authentication request
logout()
Logout from server if logged in
lookup(aEntity, lookupAttribute, aCondition, doNotUseCacheopt) → *
Lookup value in entity using aCondition.
// create condition using Repository
var myID = conn.lookup('ubm_enum', 'ID',
conn.Repository('ubm_enum').where('eGroup', '=', 'UBA_RULETYPE').where('code', '=', 'A').ubql().whereList
);
// or pass condition directly
var adminID = conn.lookup('uba_user', 'ID', {
expression: 'name', condition: 'equal', values: {nameVal: 'admin'}
});
Arguments:
-
aEntity (String)  entity to lookup
-
lookupAttribute (String)  attribute to lookup
-
aCondition (String|Object)  lookup condition. String in case of custom expression,
or whereListItem {expression: condition: values: },
or whereList {condition1: {expression: condition: values: }, condition2: {}, ....}
-
[doNotUseCache=false] (Boolean)
post(endpoint, data) → ArrayBuffer|Object|String|Array.<object>
Shortcut method to perform authorized POST request to application we connected
Arguments:
-
endpoint (String)
-
data (ArrayBuffer|Object|String)
query(ubq) → Object|Array
Perform authorized UBQL request.
Can take one QB Query or an array of UB Query and execute it at once.
Arguments:
-
ubq (Object|Array.<Object>)
Repository(entityName) → ServerRepository
Create a new instance of repository
Arguments:
-
entityName (String)  name of Entity we create for
run(request) → Object
Shortcut method to perform authorized POST request to ubql endpoint.
Can take one ubRequest and wrap it to array
Arguments:
-
request (ubRequest)
- Deprecated:
- Since UB 1.11 use SyncConnection.query
runCustom() → *
Send request to any endpoint. For entity-level method execution (ubql endpoint) better to use SyncConnection.query
setDocument(entity, attribute, id, data, origName, fileNameopt) → string
Set document method saves a file content as a potential value of the specified entity instance attribute,
the value is saved to temp store.
Call this function before entity insert of update. Result of this function is what shall be assigned to the
attribute value, to "execParams".
Arguments:
-
entity (string)  Entity name
-
attribute (string)  Entity attribute name
-
id (number)  ID of the record
-
data (ArrayBuffer)  File content
-
origName (string)
-
[fileName] (string)  If not specified, origName will be used.
Example
const myObj = conn.Repository(entityName)
.attrs('ID', 'mi_modifyDate')
.where('code', '=', code)
.selectSingle()
const {ID, mi_modifyDate} = myObj
const data = fs.readFileSync(fileName, {encoding: 'bin'})
const tempStoreResult = conn.setDocument(entityName, 'configuration', ID, data, fn)
conn.query({
entity: entityName,
method: 'update',
execParams: {ID, configuration: tempStoreResult, mi_modifyDate}
})
update()
Execute update method by add method: 'update' to ubq query (if req.method not already set)
userData(keyopt) → *
Return custom data for logged in user, or {lang: 'en'} in case not logged in
If key is provided - return only key part of user data:
$App.connection.userData('lang');
// or the same but dedicated alias
$App.connection.userLang()
Arguments:
-
[key] (String)  Optional key
userLang() → String
Return current user language or 'en' in case not logged in
userLogin() → String
Return current user logon or 'anonymous' in case not logged in
xhr(options) → ArrayBuffer|Object|String|Array.<Object>
HTTP request to UB server. In case of success response return body parsed to {Object} or {ArrayBuffer} depending of Content-Type response header
Arguments:
-
options (Object)
Properties
-
endpoint (String)
-
[UBMethod] (String)  This parameter is DEPRECATED. Use options.endpoint instead
-
[HTTPMethod='POST'] (String)
-
[headers] (Object)  Optional request headers in format {headerName: headerValue, ..}
-
[simpleTextResult=false] (Boolean)  do not parse response and return it as is even if response content type is JSON
-
[URLParams] (*)  Optional parameters added to URL using http.buildURL
-
[data] (ArrayBuffer|Object|String)  Optional body
-
[responseType] (String)  see responseType.
Currently only arraybuffer supported.
Example
conn.xhr({
endpoint: 'runSQL',
URLParams: {CONNECTION: 'dba'},
data: 'DROP SCHEMA IF EXISTS ub_autotest CASCADE; DROP USER IF EXISTS ub_autotest;'
});
SyncConnection as a parameter, must return authorization parameters object:
{authSchema: authType, login: login, password: password, [apiKey: ]}For a internal usage (requests from a locahost or other systems, etc.) and in case authShema == 'UB' it is possible to pass a
apiKey instead of a password. apiKey is actually a uba_user.uPasswordHashHexa content
runList before 1.12, ubql after 1.12)
base64 encoded server certificate used for cryptographic operation
get(endpoint, URLParamsopt) → ArrayBuffer|Object|String
endpoint with optional URLParams.
Arguments:
-
endpoint(String) -
[URLParams](*)
getAppInfo() → Object
getAppInfo endpoint
getDocument(params, optionsopt) → Promise
Retrieve content of document type attribute field from server. Usage samples:
//Retrieve content of document as string using GET
let frmContent = conn.getDocument({
entity:'ubm_form',
attribute: 'formDef',
ID: 100000232003
})
console.log(typeof frmContent)
//The same, but using POST for bypass cache
let frmContent = conn.getDocument({
entity:'ubm_form',
attribute: 'formDef',
ID: 100000232003
}, {
bypassCache: true
})
console.log(typeof frmContent) // string
//Retrieve content of document as ArrayBuffer and bypass cache
let frmContent = conn.getDocument({
entity:'ubm_form',
attribute: 'formDef',
ID: 100000232003
}, {
bypassCache: true, resultIsBinary: true
})
console.log('Result is', typeof frmContent, 'of length' , frmContent.byteLength, 'bytes'); //output: Result is object of length 2741 bytes
Arguments:
-
params(Object)Properties
-
entity(String) Code of entity to retrieve from -
attribute(String) documenttype attribute code -
id(Number) Instance ID -
[forceMime](String) If passed and server support transformation from source MIME type toforceMimeserver perform transformation and return documenRt representation in the passed MIME -
[revision](Number) Optional revision of the documnet (if supported by server-side store configuration). Default is current revision. -
[fileName](String) ???? -
[isDirty=false](Boolean) Optional ability to retrieve document in dirty state -
[store](String) ????
-
-
[options](Object) Additional request optionsProperties
getDomainInfo(isExtendedopt) → UBDomain
Arguments:
-
[isExtended=false](Boolean) For member of admin group cen return a addinitonal domain information, such as mappings, connection details, indexes
insert(ubq) → *
Execute insert method by add method: 'insert' to ubq query (if req.method not already set)
If ubq.fieldList contain only ID return inserted ID, else return array of attribute values passed to fieldList.
If no field list passed at all - return response.resultData (null usually).
var testRole = conn.insert({
entity: 'uba_role',
fieldList: ['ID', 'mi_modifyDate'],
execParams: {
name: 'testRole1',
allowedAppMethods: 'runList'
}
});
console.log(testRole); //[3000000000200,"2014-10-21T11:56:37Z"]
var testRoleID = conn.insert({
entity: 'uba_role',
fieldList: ['ID'],
execParams: {
name: 'testRole1',
allowedAppMethods: 'runList'
}
});
console.log(testRoleID); //3000000000200
Arguments:
-
ubq(ubRequest)
isAuthorized() → boolean
logout()
lookup(aEntity, lookupAttribute, aCondition, doNotUseCacheopt) → *
Lookup value in entity using aCondition.
// create condition using Repository
var myID = conn.lookup('ubm_enum', 'ID',
conn.Repository('ubm_enum').where('eGroup', '=', 'UBA_RULETYPE').where('code', '=', 'A').ubql().whereList
);
// or pass condition directly
var adminID = conn.lookup('uba_user', 'ID', {
expression: 'name', condition: 'equal', values: {nameVal: 'admin'}
});
Arguments:
-
aEntity(String) entity to lookup -
lookupAttribute(String) attribute to lookup -
aCondition(String|Object) lookup condition. String in case of custom expression, or whereListItem {expression: condition: values: }, or whereList {condition1: {expression: condition: values: }, condition2: {}, ....} -
[doNotUseCache=false](Boolean)
post(endpoint, data) → ArrayBuffer|Object|String|Array.<object>
POST request to application we connected
Arguments:
-
endpoint(String) -
data(ArrayBuffer|Object|String)
query(ubq) → Object|Array
Arguments:
-
ubq(Object|Array.<Object>)
Repository(entityName) → ServerRepository
Arguments:
-
entityName(String) name of Entity we create for
run(request) → Object
POST request to ubql endpoint.
Can take one ubRequest and wrap it to array
Arguments:
-
request(ubRequest)
- Deprecated:
- Since UB 1.11 use SyncConnection.query
runCustom() → *
ubql endpoint) better to use SyncConnection.query
setDocument(entity, attribute, id, data, origName, fileNameopt) → string
Arguments:
-
entity(string) Entity name -
attribute(string) Entity attribute name -
id(number) ID of the record -
data(ArrayBuffer) File content -
origName(string) -
[fileName](string) If not specified, origName will be used.
Example
const myObj = conn.Repository(entityName)
.attrs('ID', 'mi_modifyDate')
.where('code', '=', code)
.selectSingle()
const {ID, mi_modifyDate} = myObj
const data = fs.readFileSync(fileName, {encoding: 'bin'})
const tempStoreResult = conn.setDocument(entityName, 'configuration', ID, data, fn)
conn.query({
entity: entityName,
method: 'update',
execParams: {ID, configuration: tempStoreResult, mi_modifyDate}
})
update()
ubq query (if req.method not already set)
userData(keyopt) → *
Return custom data for logged in user, or {lang: 'en'} in case not logged in
If key is provided - return only key part of user data:
$App.connection.userData('lang');
// or the same but dedicated alias
$App.connection.userLang()
Arguments:
-
[key](String) Optional key
userLang() → String
userLogin() → String
xhr(options) → ArrayBuffer|Object|String|Array.<Object>
Arguments:
-
options(Object)Properties
-
endpoint(String) -
[UBMethod](String) This parameter is DEPRECATED. Useoptions.endpointinstead -
[HTTPMethod='POST'](String) -
[headers](Object) Optional request headers in format {headerName: headerValue, ..} -
[simpleTextResult=false](Boolean) do not parse response and return it as is even if response content type is JSON -
[URLParams](*) Optional parameters added to URL using http.buildURL -
[data](ArrayBuffer|Object|String) Optional body -
[responseType](String) see responseType. Currently onlyarraybuffersupported.
-
Example
conn.xhr({
endpoint: 'runSQL',
URLParams: {CONNECTION: 'dba'},
data: 'DROP SCHEMA IF EXISTS ub_autotest CASCADE; DROP USER IF EXISTS ub_autotest;'
});