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 : Object instance #

Application settings transferred form a server

appName : String instance #

UB application name

baseURL : String instance #

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

domain : UBDomain instance #

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

lastLoginName : String instance #

Last successful login name. Filled AFTER first 401 response

preferredLocale : string instance #

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

recorderEnabled : Boolean instance #

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

serverUrl : string instance #

UB Server URL with protocol and host.

SHA256 instance #

Calc SHA256 from string

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

ubNotifier : UBNotifierWSProtocol instance #

WebSocket ubNotifier protocol instance

Methods

addNew(serverRequest : Object)→Promise instance #

Promise of running UBQL command with addNew method (asynchronously). 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);

Arguments info:

authHandshakeCERT()→Promise instance #

CERT auth schema implementation

authHandshakeCERT2()→Promise instance #

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)→Promise instance #

UB Auth schema implementation

authHandshakeUBIP(authParams)→Promise instance #

UBIP Auth schema implementation

authorize(isRepeatopt : boolean)→<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.

Arguments info:

  • isRepeat: boolean

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

cacheClearAll()→Promise instance #

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

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

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

Arguments info:

  • root: String

    This is usually entity name

  • attributes: <string>

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

cacheOccurrenceRefresh(root : String, cacheType : cacheTypes)→Promise instance #

Refresh all cache occurrence for root depending on cacheType:

Arguments info:

cacheOccurrenceRemove(root : String, cacheType : String)→Promise instance #

Remove all cache occurrence for root depending on cacheType:

Arguments info:

checkChannelEncryption(session : UBSession, cfg : Object)→boolean instance #

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)→Promise instance #

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

Arguments info:

  • serverRequest: Object

    Request to execute

  • 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)→Object instance #

Call a LocalDataStore#doFilterAndSort - see a parameters there

get(url : string, configopt : Object)→Promise instance #

Shortcut method to perform authorized GET request to application we connected

Arguments info:

  • url: string

    Relative or absolute URL specifying the destination of the request

  • config: Object

    Optional configuration object as in {xhr}

getAppInfo()→Promise instance #

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

getDocument(params : Object, optionsopt : Object)→Promise instance #

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
  });

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

  • 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()→Promise instance #

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

initCache(userDbVersion : Number)→Promise instance #

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)→Promise instance #

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

Arguments info:

  • serverRequest: Object

    Request to execute

  • serverRequest: Object

    Request to execute

  • allowBuffer: Boolean

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

isAuthorized()→boolean instance #

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)→Promise instance #

Shortcut method to perform authorized POST request to application we connected

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)→Promise instance #

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)

Arguments info:

Repository(entityName : String)→ClientRepository instance #

Create a new instance of repository

Arguments info:

  • entityName: String

    name of Entity we create for

runTrans(ubRequestArray : <ubRequest>)→Promise instance #

Execute numbers of ubRequest in one server request (one transaction)

 $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);

select(serverRequest : Object, bypassCacheopt : Boolean)→Promise instance #

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

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

  • 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: <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)→String instance #

Return server-side error message by error number

setDocument(content : *, params : Object, onProgressopt : function)→<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.

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

  • 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

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

Example:

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

Arguments info:

  • serverRequest: Object

    Request to execute

  • serverRequest: Object

    Request to execute

  • allowBuffer: Boolean

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

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()→String instance #

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

userLogin()→String instance #

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

xhr(config : xhr)→Promise instance #

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: xhr

    Request configuration as described in

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

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