new UBConnection(connectionParams: Object)#
Mixes In:

Connection to the UnityBase server (for asynchronous client like NodeJS or Browser)

In case host set to value other then location.host server must be configured to accept CORS requests. This is usually done by setting "HTTPAllowOrigin" server configuration option.

Recommended way to create a UBConnection is UB.connect method

In case you need to create connection directly (for example in case of multiple connection from one page) the usage sample is:

   const UB = require('@ubitybase/ub-pub')
   const UBConnection = UB.UBConnection
   // connect using UBIP schema
   let conn = new UBConnection({
     host: 'http://127.0.0.1:888',
     requestAuthParams: function(conn, isRepeat){
       if (isRepeat){
         throw new UB.UBAbortError('invalid credential')
       } else {
         return Promise.resolve({authSchema: 'UBIP', login: 'admin'})
       }
     }
   })
   conn.query({entity: 'uba_user', method: 'select', fieldList: ['ID', 'name']}).then(UB.logDebug)

   // Anonymous connect. Allow access to entity methods, granted by ELS rules to `Anonymous` role
   // Request below will be success if we grant a `ubm_navshortcut.select` to `Anonymous` on the server side
   let conn = new UBConnection({
     host: 'http://127.0.0.1:888'
   })
   conn.query({entity: 'ubm_navshortcut', method: 'select', fieldList: ['ID', 'name']}).then(UB.logDebug)

UBConnection mixes an EventEmitter, so you can subscribe for authorized and authorizationFail events:

   conn.on('authorizationFail', function(reason){
        // indicate user credential is wrong
   })

   conn.on('authorized', function(ubConnection, session, authParams){console.debug(arguments)} )

Members

appConfig: Objectinstance #

Application settings transferred form a server

appName: Stringinstance #

UB application name

baseURL: Stringinstance #

The base of all urls of your requests. Will be prepend to all urls while call UB.xhr

domain: UBDomaininstance #

Domain information. Initialized after promise, returned by by function getDomainInfo is resolved

lastLoginName: Stringinstance #

Last successful login name. Filled AFTER first 401 response

preferredLocale: stringinstance #

The preferred (used in previous user session if any or a default for application) locale

recorderEnabled: Booleaninstance #

Set it to true for memorize all requests to recordedXHRs array (for debug only!).

serverUrl: stringinstance #

UB Server URL with protocol and host.

SHA256instance #

Calc SHA256 from string

var shaAsSting = SHA256('something').toString()

ubNotifier: UBNotifierWSProtocolinstance #

WebSocket ubNotifier protocol instance

Methods

addNew(serverRequest: Object)→Promise<Object>instance#

Promise of running UBQL command with addNew method (asynchronously).

Response "data" is an array of default values for row.

Two difference from UBConnection.query:

  • ubRequest.method set to 'addnew'
  • requests is always buffered in the 20ms period into one ubql call
  • Date & 'DateTime' entity attributes are converted from ISO8601 text representation to javaScript Date object

Example:

 $App.connection.addNew({entity: 'uba_user', fieldList: ['*']}).then(UB.logDebug)
 // [{"entity":"uba_user","fieldList":["ID","isPending"],"method":"addnew","resultData":{"fields":["ID","isPending"],"rowCount": 1, "data":[[332462711046145,0]]}}]

Arguments info:

addNewAsObject(serverRequest: Object, fieldAliasesopt: Object<string, string>)→Promise<Object>instance#

Promise of running UBQL command with addNew method (asynchronously).

Result is Object with default values for row.

Example:

 $App.connection.addNewAsObject({"entity":"uba_user"}).then(UB.logDebug)
 // result is {ID: 332462709833729, isPending: false}

Arguments info:

  • serverRequest: Object

    Request to execute

  • fieldAliases: Object<string, string>

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

authHandshakeCERT()→Promiseinstance#

CERT auth schema implementation

authHandshakeCERT2()→Promiseinstance#

CERT2 auth schema implementation

authHandshakeOpenIDConnect(authParams)→*instance#

openID Connect auth schema. This function act as a proxy but change authSchema back to 'UB' for authorization token generation

authHandshakeUB(authParams)→Promiseinstance#

UB Auth schema implementation

authHandshakeUBIP(authParams)→Promiseinstance#

UBIP Auth schema implementation

authorize(isRepeatopt: boolean)→Promise<UBSession>instance#

The starter method for all authorized requests to UB server. Return authorization promise resolved to UBSession. In case unauthorized:

  • call requestAuthParams method passed to UBConnection constructor to retrieve user credentials
  • call UBConnection#doAuth method

Used inside UBConnection#xhr, therefore developer rarely call it directly.

Return:

Resolved to {UBSession} if auth success or rejected to {errMsg: string, errCode: number, errDetails: string} if fail

Arguments info:

  • isRepeat: boolean

    in case user provide wrong credential - we must show logon window

cacheClearAll()→Promiseinstance#

Clear all local cache (indexedDB session & permanent and UBConnection.cachedSessionEntityRequested)

cacheKeyCalculate(root: String, attributesopt: Array<string>)→Stringinstance#

Calculate cache key for request. This key is used to store data inside UBCache

Arguments info:

  • root: String

    This is usually entity name

  • attributes: Array<string>

    if present - add attributes hash. This is usually array of entity attributes we want to put inside cache

cacheOccurrenceRefresh(root: String, cacheType: UBCache.cacheTypes)→Promiseinstance#

Refresh all cache occurrence for root depending on cacheType:

Arguments info:

cacheOccurrenceRemove(root: String, cacheType: String)→Promiseinstance#

Remove all cache occurrence for root depending on cacheType:

Arguments info:

checkChannelEncryption(session: UBSession, cfg: Object)→booleaninstance#

convertResponseDataToJsTypes(serverResponse)→*instance#

Convert raw server response data to javaScript data according to attribute types. Called by UBConnection#select Currently only Data/DateTime & boolean conversion done If resultLock present - resultLock.lockTime also converted

 // convert all string representation of date/dateTime to Date object, integer representation of bool to Boolean
 return me.query({entity: 'my_entity', method: 'select'}, true)
     .then(me.convertResponseDataToJsTypes.bind(me));

doDelete(serverRequest: Object, allowBufferopt: Boolean)→Promiseinstance#

Promise of running UBQL command with delete method (asynchronously). Difference from UBConnection.query:

  • ubRequest.method set to 'delete' by default
  • if necessary it will clear cache

Return:

Example:

 $App.connection.doDelete({entity: 'uba_user', fieldList: ['ID','name'], execParams: {ID: 1, name:'newName'}).then(UB.logDebug);

Arguments info:

  • serverRequest: Object

    Request to execute

  • allowBuffer: Boolean

    Default - false. Allow several "in the same time" request to be buffered to one transaction.

doFilterAndSort(cachedData: TubCachedData, ubql: UBQL)→Objectinstance#

Call a LocalDataStore#doFilterAndSort - see a parameters there

get(url: string, configopt: Object)→Promiseinstance#

Shortcut method to perform authorized GET request to application we connected

Return:

Future object

Arguments info:

  • url: string

    Relative or absolute URL specifying the destination of the request

  • config: Object

    Optional configuration object as in {xhr}

getAppInfo()→Promiseinstance#

Retrieve application information. Usually this is first method developer must call after create connection

Return:

Promise resolved to result of getAppInfo method

getDocument(params: Object, optionsopt: Object)→Promiseinstance#

Retrieve content of document type attribute field from server. Usage samples:

 //Retrieve content of document as string using GET
 $App.connection.getDocument({
     entity:'ubm_form',
     attribute: 'formDef',
     ID: 100000232003
  }).then(function(result){console.log(typeof result)}); // string

 //The same, but using POST for bypass cache
 $App.connection.getDocument({
     entity:'ubm_form',
     attribute: 'formDef',
     ID: 100000232003
  }, {
     bypassCache: true
  }).then(function(result){console.log(typeof result)}); // string


 //Retrieve content of document as ArrayBuffer and bypass cache
 $App.connection.getDocument({
     entity:'ubm_form',
     attribute: 'formDef',
     ID: 100000232003
  }, {
     bypassCache: true, resultIsBinary: true
  }).then(function(result){
     console.log('Result is', typeof result, 'of length' , result.byteLength, 'bytes'); //output: Result is object of length 2741 bytes
  });

Return:

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

Arguments info:

  • params: Object
    • 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 document (if supported by server-side store configuration). Default is current revision.

    • fileName: String

      ????

    • isDirty: Boolean

      Optional ability to retrieve document in dirty state

    • store: String

      ????

  • options: Object
    • resultIsBinary: Boolean

      if true - return document content as arrayBuffer

    • bypassCache: Boolean

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

    Additional request options

getDomainInfo()→Promiseinstance#

Retrieve domain information from server. Promise resolve instance of UBDomain.

initCache(userDbVersion: Number)→Promiseinstance#

Initialize client cache. Called from application after obtain userDbVersion

  • recreate Indexed Db database if version changed
  • create instance of UBCache (accessible via UBConnection.cache property) and clear UBCache.SESSION store.

Arguments info:

  • userDbVersion: Number

    Indexed DB database version required for current application

insert(serverRequest: Object, allowBufferopt: Boolean)→Promiseinstance#

Promise of running UnityBase UBQL command with insert method (asynchronously). Difference from UBConnection.query:

  • ubRequest.method set to 'insert'
  • Date & 'DateTime' entity attributes are converted from ISO8601 text representation to javaScript Date object
  • if necessary it will clear cache

Return:

Example:

 $App.connection.insert({entity: 'uba_user', fieldList: ['ID','name'], execParams: {ID: 1, name:'newName'}).then(UB.logDebug);

Arguments info:

  • serverRequest: Object

    Request to execute

  • allowBuffer = false : Boolean

    Allow several "in the same time" request to be buffered to one transaction.

insertAsObject(serverRequest: Object, fieldAliasesopt: Object<string, string>, allowBufferopt: Boolean)→Promise<Object>instance#

Promise of running UnityBase UBQL command with insert method (asynchronously).

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

Return:

Example:

$App.connection.insertAsObject({"entity":"uba_user","fieldList":['ID', 'name', 'mi_modifyDate'], execParams: {name: 'insertedName'}}).then(UB.logDebug) // {ID: 332462911062017, mi_modifyDate: Tue Apr 23 2019 17:04:30 GMT+0300 (Eastern European Summer Time), name: "insertedname"}

Arguments info:

  • serverRequest: Object
    • entity: String

      Entity to execute the method

    • method='insert': String

      Method of entity to executed

    • fieldList: Array<string>

      Attributes to be returned in result

    • execParams: Object

      Attributes values to be inserted. If ID is omitted it will be autogenerated

    • options: Object

    • lockType: String

    • alsNeed: Boolean

    Request to execute

  • fieldAliases: Object<string, string>

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

  • allowBuffer = false : Boolean

    Allow several "in the same time" request to be buffered to one transaction.

isAuthorized()→booleaninstance#

Is user currently logged in. There is no guaranty what session actually exist in server.

logout()instance#

Log out user from server

post(url: string, data: *, configopt: Object)→Promiseinstance#

Shortcut method to perform authorized POST request to application we connected

Return:

Future object

Arguments info:

  • url: string

    Relative or absolute URL specifying the destination of the request

  • data: *

    Request content

  • config: Object

    Optional configuration object as in {xhr}

query(ubq: Object, allowBufferopt: Boolean)→Promiseinstance#

Promise of running UBQL command(s) (asynchronously). The difference from UBConnection.post is:

  • ability to buffer request: can merge several query in the 20ms period into one ubql call

For well known UnityBase methods use aliases (addNew, select, insert, update, doDelete)

Return:

Example:

 //this two execution is passed to single ubql server execution
 $App.connection.query({entity: 'uba_user', method: 'select', fieldList: ['*']}, true).then(UB.logDebug);
 $App.connection.query({entity: 'ubm_navshortcut', method: 'select', fieldList: ['*']}, true).then(UB.logDebug);

 //but this request is passed in separate ubql (because allowBuffer false in first request
 $App.connection.query({entity: 'uba_user', method: 'select', fieldList: ['*']}).then(UB.logDebug);
 $App.connection.query({entity: 'ubm_desktop', method: 'select', fieldList: ['*']}, true).then(UB.logDebug);

Arguments info:

  • ubq: Object

    Request to execute

  • allowBuffer: Boolean

    Allow buffer this request to single runList. False by default

Repository(entityName: String)→ClientRepositoryinstance#

Create a new instance of repository

Arguments info:

  • entityName: String

    name of Entity we create for

runTrans(ubRequestArray: Array<ubRequest>)→Promiseinstance#

Group several ubRequest into one server request (executed in singe transaction on server side)

 $App.connection.runTrans([
      { entity: 'my_entity', method: 'update', ID: 1, execParams: {code: 'newCode'} },
      { entity: 'my_entity', method: 'update', ID: 2, execParams: {code: 'newCodeforElementWithID=2'} },
  ]).then(UB.logDebug);

Return:

Resolved to response.data

runTransAsObject(ubRequestArray: Array<ubRequest>, fieldAliasesArrayopt: Array<Object<string, string>>)→Promise<Array<Object>>instance#

Group several ubRequest into one server request (executed in singe transaction on server side)

Each response will be returned in the same array position as corresponding request.

In case response contains resultData property of type {data: fields: } it will be converted to array-of-object dataStore format

In case method is insert or update array is replaced by first element. Example below use one entity, but real app can use any combination of entities and methods

   $App.connection.runTransAsObject([
     {entity: "tst_aclrls", method: 'insert', fieldList: ['ID', 'caption'], execParams: {caption: 'inserted1'}},
     {entity: "tst_aclrls", method: 'insert', opaqueParam: 'insertWoFieldList', execParams: {caption: 'inserted2'}},
     {entity: "tst_aclrls", method: 'update', fieldList: ['ID', 'caption'], execParams: {ID: 332463213805569, caption: 'updated1'}},
     {entity: "tst_aclrls", method: 'delete', execParams: {ID: 332463213805572}}]
   ).then(UB.logDebug)
   // result is:
   [{
      "entity": "tst_aclrls","method": "insert","fieldList": ["ID","caption"],"execParams": {"caption": "inserted1","ID": 332463256010753},
      "resultData": {"ID": 332463256010753,"caption": "inserted1"}
     },
     {
      "entity": "tst_aclrls","method": "insert","opaqueParam": "insertWoFieldList","execParams": {"caption": "inserted2","ID": 332463256010756},"fieldList": []
     },
     {
      "entity": "tst_aclrls","method": "update","fieldList": ["ID","caption"],"execParams": {"ID": 332463213805569,"caption": "updated1"},
      "resultData": {"ID": 332463213805569,"caption": "updated1"}
     },
     {
      "entity": "tst_aclrls","method": "delete","execParams": {"ID": 332463213805572},
      "ID": 332463213805572
     }
   ]

Arguments info:

  • fieldAliasesArray: Array<Object<string, string>>

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

select(serverRequest: Object, bypassCacheopt: Boolean)→Promiseinstance#

Promise of running UBQL (asynchronously). Two difference from UBConnection.query:

  • ubRequest.method by default set to 'select'
  • requests is always buffered in the 20ms period into one ubql call
  • Date & 'DateTime' entity attributes are converted from ISO8601 text representation to javaScript Date object
  • if request entity is cached - cache used

Return:

Example:

 //retrieve users
 $App.connection.select({entity: 'uba_user', fieldList: ['*']}).then(UB.logDebug);

 //retrieve users and desktops and then both done - do something
 Promise.all($App.connection.select({entity: 'uba_user', fieldList: ['ID', 'name']})
   $App.connection.select({entity: 'ubm_desktop', fieldList: ['ID', 'code']})
 ).then(UB.logDebug);

Arguments info:

  • serverRequest: Object
    • entity: String

      Entity to execute the method

    • method: String

      Method of entity to executed. Default to 'select'

    • ID: Number

      if passed - request bypass cache, where & order list is ignored. Can be used to load single record from server

    • fieldList: Array<string>

    • whereList: Object

    • execParams: Object

    • options: Object

    • lockType: String

    • alsNeed: Boolean

    • __skipOptimisticLock: Boolean

      In case this parameter true and in the buffered

    Request to execute

  • bypassCache = false : Boolean

    Do not use cache while request even if entity cached. If __mip_disablecache: true is passed in serverRequest cache is also disabled.

serverErrorByCode(errorNum: Number)→Stringinstance#

Return server-side error message by error number

setDocument(content: *, params: Object, onProgressopt: function)→Promise<Object>instance#

Saves a file content to the TEMP store of the specified entity attribute of Document type.

Should be called before insert of update. Result of this function is what shall be assigned to the attribute value during insert/update operation.

Return:

Promise resolved blob store metadata

Arguments info:

  • params: Object
    • entity: string

      Entity name

    • attribute: string

      Entity attribute name

    • id: number

      ID of the record

    • origName: string

    • fileName: string

      If not specified, params.origName will be used

    • encoding: string

      Encoding of data. Either omit for binary data or set to base64 for base64 encoded data

    Additional parameters

  • content: *

    BLOB attribute content

  • onProgress: function

    Optional onProgress callback

setRequestAuthParamsFunction(authParamsFunc: function)instance#

Allow to override a connection requestAuthParams function passed as config to UBConnection instance

Arguments info:

  • authParamsFunc: function

    Function with the same signature as requestAuthParams parameter in UBConnection constructor

update(serverRequest: Object, allowBufferopt: Boolean)→Promise<Object>instance#

Promise of running UBQL command with update method (asynchronously). Difference from UBConnection.query:

  • ubRequest.method set to 'update'
  • Date & 'DateTime' entity attributes are converted from ISO8601 text representation to javaScript Date object
  • if necessary it will clear cache

In case fieldList is passed - result will contains updated values for attributes specified in fieldList in Array representation

Example:

 $App.connection.update({
   entity: 'uba_user',
   fieldList: ['ID','name', 'mi_modifyDate'],
   execParams: {ID: 332462122205200, name:'test', mi_modifyDate:"2019-04-23T13:00:00Z"}
 }).then(UB.logDebug);
 // [{"entity":"uba_user","fieldList":["ID","name","mi_modifyDate"],"execParams":{"ID":332462122205200,"name":"test","mi_modifyDate":"2019-04-23T13:03:51Z","mi_modifyUser":10},"method":"update","resultData":{"fields":["ID","name","mi_modifyDate"],"rowCount": 1, "data":[[332462122205200,"test","2019-04-23T13:03:51Z"]]}}]

Arguments info:

  • serverRequest: Object

    Request to execute

  • allowBuffer = false : Boolean

    Allow several "in the same time" request to be buffered to one transaction.

updateAsObject(serverRequest: Object, allowBufferopt: Boolean, fieldAliasesopt: Object<string, string>)→Promise<Object>instance#

Promise of running UBQL command with update method (asynchronously).

In case fieldList is passed - result will contains updated values for attributes specified in fieldList as Object;

If fieldList is not passed or empty - return null

Example:

 $App.connection.updateAsObject({
   entity: 'uba_user',
   fieldList: ['ID','name','mi_modifyDate', 'isPending'],
   execParams: {ID: 33246, name:'newName', mi_modifyDate:"2019-04-23T13:00:00Z"}
 }).then(UB.logDebug);
 // {"ID": 332462122205200, "name": newName", "mi_modifyDate": new Date("2019-04-23T13:03:51Z"), isPending: false}

Arguments info:

  • serverRequest: Object

    Request to execute

  • allowBuffer = false : Boolean

    Allow several "in the same time" request to be buffered to one transaction.

  • fieldAliases: Object<string, string>

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

userData(keyopt: String)→*instance#

Return custom data for logged in user, or {lang: 'en', login: 'anonymous'} in case not logged in

If key is provided - return only key part of user data. For a list of possible keys see Session.uData in server side documentation.

Arguments info:

Examples

    
        $App.connection.userData('lang');
// or the same but dedicated alias
$App.connection.userLang()
    
userLang()→Stringinstance#

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

userLogin()→Stringinstance#

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

xhr(config: transport.xhr)→Promiseinstance#

Shortcut method to perform authorized/encrypted request to application we connected. Will:

  • add Authorization header for non-anonymous sessions
  • add UBConnection#baseURL to config.url
  • call transport.xhr
  • in case server return 401 clear current authorization, call {UBConnection#authorize) and repeat the request

Arguments info:

  • config: transport.xhr

    Request configuration as described in

doCreateNewSession(data, secretWord, authSchema, restoredopt: Boolean)→UBSessioninner#

Arguments info:

  • restored = false : Boolean

    true in case session is restored from persistent storage

doOnCredentialsRequired(conn: UBConnection, isRepeat: Boolean)→*inner#

For a browser env. check silence kerberos login {@see UB.connect UB.connect} for details