Synchronous server-side connection to the UnityBase instance. To be used only inside UnityBase. For Node.js & browser use asynchronous UBConnection class from @unitybase/ub-pub package.

The most used method is SyncConnection.query - an authorized request to ubql endpoint.

  
      const SyncConnection = require('@unitybase/base').SyncConnection
const conn = new SyncConnection({URL: 'http://localhost:888'})
conn.onRequestAuthParams = function(){ return {authSchema: 'UB', login: 'admin', password: 'admin'} }
const domain = conn.getDomainInfo();
if (domain.has('my_entity')){
 ..
}
  

# new SyncConnection (optionsobject)

Arguments:

Members

# appConfig : object instance

AdminUI settings

# appName : string instance

Name of UnityBase application

# authMethods : Array.<string> instance

Possible server authentication method

# authNeed : boolean instance

Is UnityBase server require authorization

# clientRequest : ClientRequest instance

Internal instance of HTTP client

# encryptContent : boolean instance

Is server require content encryption

# onRequestAuthParams : function instance

Callback for resolving user credential. Take a SyncConnection as a parameter, must return authorization parameters object:

 {authSchema: authType, login: login, password: password, [apiKey: ]}

For an internal usage (requests from a localhost 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 instance

Endpoint name for query (runList before 1.12, ubql after 1.12)

# serverCertificate : boolean instance

base64 encoded server certificate used for cryptographic operation

# servicePath : string instance

Root path to all application-level method

# sessionKeyLifeTime : number instance

Lifetime (in second) of session encryption

# UBQLv2 instance

Server support UBQL v2 (value instead of values)

Name Type Description
UBQLv2 boolean

# _domain : UBDomain inner

Methods

# addNew (ubqubRequest) → * instance

Execute addnew method: add method 'addnew' to ubq query (if req.method not already set)

If ubq.fieldList contain only ID return generated ID, otherwise return array of attribute values passed to fieldList. If no field list passed at all - return response.resultData (null usually).

Arguments:
  
      const testRole = conn.addNew({
  entity: 'uba_role',
  fieldList: ['ID', 'name', 'allowedAppMethods'],
  execParams: {
    name: 'testRole1',
    allowedAppMethods: 'runList'
  }
})
console.log(testRole) //[3000000000200,"testRole1","runList"]

const testRoleID = conn.addNew({
  entity: 'uba_role',
  fieldList: ['ID']
})
console.log(testRoleID) //3000000000200
  

# addNewAsObject (ubqubRequest, fieldAliasesoptObject.<string, string>) → object instance

Run UBQL command with addnew method

In case fieldList is passed - result will contains new values for attributes specified in fieldList as Object, otherwise - null

In opposite to addNew method values in result are PARSED based on Domain (as in AsyncConnection) - so values for boolean attributes is true/false, date is typeof Date etc.

Arguments:
  • ubq: ubRequest
  • fieldAliases: Object.<string, string>

    Optional object to change attribute names during transform array to object. Keys are original names, values - new names

  
      const newRole = conn.addNewAsObject({
  entity: 'uba_role',
  fieldList: ['ID', 'name', 'allowedAppMethods'],
  execParams: {
      name: 'testRole61',
      allowedAppMethods: 'runList'
  }
})
console.log(newRole) // {ID: 332462911062017, name: 'testRole1', allowedAppMethods: 'runList'}
  

# get (endpointstring, URLParamsopt*) → ArrayBuffer | object | string instance

Perform get request to endpoint with optional URLParams.

Arguments:

# getAppInfo () → object instance

Return information about how application is configured as returned by getAppInfo endpoint

# getDocument (paramsobject, optionsoptobject) → ArrayBuffer | string instance

Retrieve content of document type attribute field from server

Return:

Document content (either ArrayBuffer in case options.resultIsBinary===true or text/json)

Arguments:
  • params: object
    • entitystring

      Code of entity to retrieve from

    • attributestring

      document type attribute code

    • idnumber

      Instance ID

    • forceMimestring

      If passed and server support transformation from source MIME type to forceMime server perform transformation and return documenRt representation in the passed MIME

    • revisionnumber

      Optional revision of the documnet (if supported by server-side store configuration). Default is current revision.

    • fileNamestring

      ????

    • isDirtyboolean

      Optional ability to retrieve document in dirty state

    • storestring

      ????

  • options: object
    • resultIsBinaryboolean

      if true - return document content as arrayBuffer

    • bypassCacheboolean

      HTTP POST verb will be used instead of GET for bypass browser cache

    Additional request options

  
      //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
  

# getDomainInfo (isExtendedoptboolean) → UBDomain instance

Retrieve application domain information.

Arguments:
  • isExtended = false: boolean

    For member of admin group can return a additional domain information, such as mappings, connection details, indexes, realPath for models etc.

# insert (ubqubRequest) → * instance

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).

Arguments:
  
      const testRole = conn.insert({
  entity: 'uba_role',
  fieldList: ['ID', 'mi_modifyDate'],
  execParams: {
      name: 'testRole1',
      allowedAppMethods: 'runList'
  }
})
console.log(testRole) //[3000000000200,"2014-10-21T11:56:37Z"]

const testRoleID = conn.insert({
  entity: 'uba_role',
  fieldList: ['ID'],
  execParams: {
      name: 'testRole1',
      allowedAppMethods: 'runList'
  }
})
console.log(testRoleID) //3000000000200
  

# insertAsObject (ubqubRequest, fieldAliasesoptObject.<string, string>) → object instance

Run UBQL command with insert method

In case fieldList is passed - result will contains new values for attributes specified in fieldList as Object, otherwise - null

In opposite to insert method values in result are PARSED based on Domain (as in AsyncConnection) - so values for boolean attributes is true/false, date is typeof Date etc.

Arguments:
  • ubq: ubRequest
  • fieldAliases: Object.<string, string>

    Optional object to change attribute names during transform array to object. Keys are original names, values - new names

  
      const newRole = conn.insertAsObject({
  entity: 'uba_role',
  fieldList: ['ID', 'name', 'allowedAppMethods', 'mi_modifyDate'],
  execParams: {
      name: 'testRole61',
      allowedAppMethods: 'runList'
  }
}, {mi_modifyDate: 'modifiedAt'})
console.log(newRole) // {ID: 332462911062017, name: 'testRole1', allowedAppMethods: 'runList', mi_modifyDate: 2020-12-21T15:45:01.000Z}
console.log(newRole.modifiedAt instanceof Date) //true
  

# isAuthorized () → boolean instance

Check is current connection already perform authentication request

# logout () instance

Logout from server if logged in

# lookup (aEntitystring, lookupAttributestring, aConditionstring | object, doNotUseCacheoptboolean) → * instance

Lookup value in entity using a Condition

Return:

lookupAttribute value of first result row or null if not found.

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: value: }, or whereList {condition1: {expression: condition: value: }, condition2: {}, ....}

  • doNotUseCache = false: boolean
  
      // create condition using Repository
const myID = conn.lookup('ubm_enum', 'ID',
  conn.Repository('ubm_enum').where('eGroup', '=', 'UBA_RULETYPE').where('code', '=', 'A').ubql().whereList
)
// or pass condition directly
const adminID = conn.lookup('uba_user', 'ID', {
 expression: 'name', condition: 'equal', value: 'admin'}
})
  

# post (endpointstring, dataArrayBuffer | object | string, URLParamsoptobject) → ArrayBuffer | object | string | Array.<object> instance

Shortcut method to perform authorized POST request to application we connected

Arguments:

# query (ubqobject) → object | Array instance

Perform authorized UBQL request. Can take one QB Query or an array of UB Query and execute it at once.

Arguments:

# Repository (entityCodeOrUBQLstring) → ServerRepository instance

Create a new instance of repository

Arguments:
  • entityCodeOrUBQL: string| object

    The name of the Entity for which the Repository is being created or UBQL

# run (requestubRequest) → object instance deprecated

Since UB 1.11 use SyncConnection.query

Shortcut method to perform authorized POST request to ubql endpoint. Can take one ubRequest and wrap it to array

Arguments:

# runCustom () → * instance

Send request to any endpoint. For entity-level method execution (ubql endpoint) better to use SyncConnection.query

Return:

body of HTTP request result. If !simpleTextResult and response type is json - then parsed to object

# setDocument (entitystring, attributestring, idnumber, dataArrayBuffer | string, origNamestring, fileNameoptstring, dataEncodingstring) → string instance

Saves a file content as a potential value of the specified entity instance attribute to the 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| string

    File content

  • origName: string
  • fileName: string

    If not specified, origName will be used.

  • dataEncoding: string

    Specify data parameter encoding. Either omit for binary data or set to base64 for base64 encoded data

  
      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 (ubqUBQL) → object instance

Execute update method (adds method: 'update' if req.method is not already set)

Arguments:

# updateAsObject (ubqubRequest, fieldAliasesoptObject.<string, string>) → object instance

Run UBQL command with update method

In case fieldList is passed - result will contain new values for attributes specified in fieldList as Object, otherwise - null

In opposite to update method values in result are PARSED based on Domain (as in AsyncConnection) - so values for boolean attributes is true/false, date is typeof Date etc.

Arguments:
  • ubq: ubRequest
  • fieldAliases: Object.<string, string>

    Optional object to change attribute names during transform array to object. Keys are original names, values - new names

  
      const newRole = conn.updateAsObject({
  entity: 'uba_role',
  fieldList: ['ID', 'name', 'allowedAppMethods', 'mi_modifyDate'],
  execParams: {
      ID: 123,
      name: 'testRole61'
  }
}, {mi_modifyDate: 'modifiedAt'})
console.log(newRole) // {ID: 332462911062017, name: 'testRole1', allowedAppMethods: 'runList', mi_modifyDate: 2020-12-21T15:45:01.000Z}
console.log(newRole.modifiedAt instanceof Date) //true
  

# userData (keyoptstring) → * instance

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

Arguments:
  
      $App.connection.userData('lang')
// or the same but dedicated alias
$App.connection.userLang()
  

# userLang () → string instance

Return current user language or 'en' in case not logged in

# userLogin () → string instance

Return current user logon or 'anonymous' in case not logged in

# xhr (optionsobject) → ArrayBuffer | object | string | Array.<object> instance

HTTP request to UB server. In case of success response return body parsed to {object} or {ArrayBuffer} depends on Content-Type response header

Arguments:
  • options: object
    • endpointstring

    • UBMethodstring

      This parameter is DEPRECATED. Use options.endpoint instead

    • HTTPMethod='POST'string

    • headersobject

      Optional request headers in format {headerName: headerValue, ...}

    • simpleTextResultboolean

      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

    • dataArrayBuffer | object | string

      Optional body

    • responseTypestring

      see responseType. Currently only arraybuffer supported.

  
      conn.xhr({
   endpoint: 'runSQL',
   URLParams: {CONNECTION: 'dba'},
   data: 'DROP SCHEMA IF EXISTS ub_autotest CASCADE; DROP USER IF EXISTS ub_autotest;'
 })