UBConnection

UBConnection

Connection to then UnityBase server.

In case host set to value other then location.host server must be configured to accept CORS requests. Usually it done via "HTTPAllowOrigin" server configuration option.

Usage sample:

   var conn = new UBConnection({
       host: 'http://127.0.0.1:888',
       requestAuthParams: function(conn, isRepeat){
           if (isRepeat){
               throw new UB.UBAbortError('invalid')
           } else {
               return Q.resolve({authSchema: 'UBIP', login: 'admin'})
           }
        }
   });
   conn.query({entity: 'uba_user', method: 'select', fieldList: ['ID', 'name']}).done(UB.logDebug);

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

Constructor

new UBConnection(connectionParams)

Arguments:
  1. connectionParams (Object)  connection parameters
    Properties
    1. host (String)  UnityBase server host
    2. [appName='/'] (String)  UnityBase application to connect to
    3. requestAuthParams (function)  Handler to log in. Must return promise & fulfill it by authorization parameters: {authSchema: authType, login: login, password: password } for openIDConnect must be fulfilled with {data: uData, secretWord: ???} Called with arguments: {UBConnection} conn, {Boolean} isRepeat; isRepeat === true in case first auth request is invalid
    4. [protocol] (String)  either 'https' or 'http' (default)
Mixes In:

Members

serverUrl: string readonly

UB Server URL with protocol and host.

baseURL: String readonly

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

appName: String readonly

UB application name

channelEncryptor: UBNativeDSTUCrypto

UBNativeDSTUCrypto instance used for encryption

lastLoginName: String

Last successful login name. Filled AFTER first 401 response

useCacheForXHR: Boolean|String

Cache flag to enable a hack appending the current timestamp to your requests to prevent IE from caching them and always returning the same result. If "true", will set the param with the name "_" If a string, will use it as the param name
Type:

recorderEnabled: Boolean

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

Methods

isPKIReady()boolean protected

Check current connection use PKI

isAuthorized()boolean

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

userLogin()String

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

userLang()String

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

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:
  1. [key] (String)  Optional key

authorize(isRepeatopt) → Promise

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:
  1. [isRepeat] (boolean)  in case user provide wrong credential - we must show logon window

authHandshakeUBIP(authParams) → Promise

UBIP Auth schema implementation
Arguments:
  1. authParams

authHandshakeOpenIDConnect(authParams) → *

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

authHandshakeUB(authParams) → Promise

UB Auth schema implementation
Arguments:
  1. authParams

authHandshakeCERT(authParams) → Promise

CERT auth schema implementation
Arguments:
  1. authParams

initCache(userDbVersion) → Promise

Initialize client cache. Called from application after obtain userDbVersion (in case of Ext-based client called from UB.core.UBApp#launch.

  • recreate Indexed Db database if version changed
  • create instance of UBCache (accessible via UBConnection.cache property) and clear UBCache.SESSION store.
Arguments:
  1. userDbVersion (Number)  Indexed DB database version required for current application

cacheKeyCalculate(root, attributesopt)String

Calculate cache key for request. This key is used to store data inside UBCache
Arguments:
  1. root (String)  This is usually entity name
  2. [attributes] (Array.<string>)  if present - add attributes hash. This is usually array of entity attributes we want to put inside cache

cacheOccurrenceRefresh(root, cacheType) → Promise

Refresh all cache occurrence for root depending on cacheType:

  • if Session - clear indexedDB for this root.
  • if SessionEntity - remove entry in UBConnection#cachedSessionEntityRequested
  • else - do nothing
Arguments:
  1. root (String)  Root part of cache key. The same as in UBConnection#cacheKeyCalculate
  2. cacheType (String)  One of UBCache#cacheTypes

cacheOccurrenceRemove(root, cacheType) → Promise

Remove all cache occurrence for root depending on cacheType:

  • clear indexedDB for this root.
  • remove entry in UBConnection#cachedSessionEntityRequested
Arguments:
  1. root (String)  Root part of cache key. The same as in UBConnection#cacheKeyCalculate
  2. cacheType (String)  One of UBCache#cacheTypes

cacheClearAll() → Promise

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

pki() → UBNativeIITCrypto

Return instance of UBNativeIITCrypto for PKI operation

exchangeKeys(session) → Promise

Perform key exchange in case of encrypted communication
Arguments:
  1. session

get(url, configopt) → Promise

Shortcut method to perform authorized GET request to application we connected
Arguments:
  1. url (string)  Relative or absolute URL specifying the destination of the request
  2. [config] (Object)  Optional configuration object as in UB.xhr

post(url, data, configopt) → Promise

Shortcut method to perform authorized POST request to application we connected
Arguments:
  1. url (string)  Relative or absolute URL specifying the destination of the request
  2. data (*)  Request content
  3. [config] (Object)  Optional configuration object as in UB.xhr

xhr(config) → Promise

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

  • add Authorization header
  • add UBConnection#baseURL to config.url
  • call UB.xhr
  • in case server return 401 clear current authorization and call {@link UBConnection#authorize). Then repeat request
Arguments:
  1. config (Object)  Request configuration as described in UB.xhr

getAppInfo() → Promise

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

getDomainInfo(callBackopt) → Promise

Retrieve domain information from server. Promise resolve instance of UBDomain.
Arguments:
  1. [callBack] (function)  This parameter will be deleted in next version

initEncriptionIfNeed() → Promise

If connection require encryption then initialize UBConnection.channelEncryptor

query(ubq, allowBufferopt) → Promise

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:
  1. ubq (Object)  Request to execute
    Properties
    1. entity (String)  Entity to execute the method
    2. method (String)  Method of entity to executed
    3. [fieldList] (Array.<String>)
    4. [whereList] (Object)
    5. [execParams] (Object)
    6. [ID] (Number)
    7. [options] (Object)
    8. [lockType] (String)
    9. [__skipOptimisticLock] (Boolean)  In case this parameter true and in the buffered
    10. [__nativeDatasetFormat] (Boolean)
  2. [allowBuffer] (Boolean)  Allow buffer this request to single runList. False by default

convertResponseDataToJsTypes(serverResponse) → *

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));
Arguments:
  1. serverResponse

doFilterAndSort(cachedData, ubRequest)Object protected

Call a LocalDataStore#doFilterAndSort - see a parameters there
Arguments:
  1. cachedData (TubCachedData)
  2. ubRequest (TubSelectRequest)

addNew(serverRequest) → Promise

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: ['*']}).done(UB.logDebug);
Arguments:
  1. serverRequest (Object)  Request to execute
    Properties
    1. entity (String)  Entity to execute the method
    2. [method] (String)  Method of entity to executed. Default to 'select'
    3. fieldList (Array.<string>)
    4. [execParams] (Object)
    5. [options] (Object)
    6. [lockType] (String)
    7. [alsNeed] (Boolean)

update(serverRequest, allowBufferopt) → Promise

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'}}).done(UB.logDebug);
Arguments:
  1. serverRequest (Object)  Request to execute
    Properties
    1. entity (String)  Entity to execute the method
    2. [method] (String)  Method of entity to executed. Default to 'update'
    3. fieldList (Array.<string>)
    4. [execParams] (Object)
    5. [options] (Object)
    6. [lockType] (String)
    7. [alsNeed] (Boolean)
  2. [allowBuffer] (Boolean)  Default - false. Allow several "in the same time" request to be buffered to one transaction.

insert(serverRequest, allowBufferopt) → Promise

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:
  1. serverRequest (Object)  Request to execute
    Properties
    1. entity (String)  Entity to execute the method
    2. [method] (String)  Method of entity to executed. Default to 'insert'
    3. fieldList (Array.<string>)
    4. [execParams] (Object)
    5. [options] (Object)
    6. [lockType] (String)
    7. [alsNeed] (Boolean)
  2. [allowBuffer] (Boolean)  Default - false. Allow several "in the same time" request to be buffered to one transaction.

doDelete(serverRequest, allowBufferopt) → Promise

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:
  1. serverRequest (Object)  Request to execute
    Properties
    1. entity (String)  Entity to execute the method
    2. [method] (String)  Method of entity to executed. Default to 'delete'
    3. [execParams] (Object)
    4. [options] (Object)
    5. [lockType] (String)
    6. [alsNeed] (Boolean)
  2. [allowBuffer] (Boolean)  Default - false. Allow several "in the same time" request to be buffered to one transaction.

select(serverRequest, bypassCacheopt) → Promise

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:
  1. serverRequest (Object)  Request to execute
    Properties
    1. entity (String)  Entity to execute the method
    2. [method] (String)  Method of entity to executed. Default to 'select'
    3. [ID] (Number)  if passed - request bypass cache, where & order list is ignored. Can be used to load single record from server
    4. fieldList (Array.<string>)
    5. [whereList] (Object)
    6. [execParams] (Object)
    7. [options] (Object)
    8. [lockType] (String)
    9. [alsNeed] (Boolean)
    10. [__skipOptimisticLock] (Boolean)  In case this parameter true and in the buffered
  2. [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.

runTrans(ubRequestArray) → Promise

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'} },
  ]).done(UB.logDebug);
Arguments:
  1. ubRequestArray (Array.<ubRequest>)

getDocument(params, optionsopt) → Promise

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
  }).done(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
  }).done(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
  }).done(function(result){
     console.log('Result is', typeof result, 'of length' , result.byteLength, 'bytes'); //output: Result is object of length 2741 bytes
  });
Arguments:
  1. params (Object)
    Properties
    1. entity (String)  Code of entity to retrieve from
    2. attribute (String)  document type attribute code
    3. id (Number)  Instance ID
    4. [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
    5. [revision] (Number)  Optional revision of the documnet (if supported by server-side store configuration). Default is current revision.
    6. [fileName] (String)  ????
    7. [isDirty=false] (Boolean)  Optional ability to retrieve document in dirty state
    8. [store] (String)  ????
  2. [options] (Object)  Additional request options
    Properties
    1. [resultIsBinary=false] (Boolean)  if true - return document content as arrayBuffer
    2. [bypassCache] (Boolean)  HTTP POST verb will be used instead of GET for bypass browser cache

logout()

Log out user from server

serverErrorByCode(errorNum)String

Return server-side error message by error number
Arguments:
  1. errorNum (Number)

listenerCount(emitter, type)Number

Return the number of listeners for a given event.
Arguments:
  1. emitter (EventEmitter)
  2. type (String)
Mixes In: