JavaScript Style Guide

Data layer for accessing UnityBase server from Browser or NodeJS

NodeJS example:

global.XMLHttpRequest = require('xhr2')

const UB = require('@unitybase/ub-pub')

let conn = UB.connect({
  host: 'http://localhost:8881',
  onCredentialRequired: function (conn, isRepeat) {
    if (isRepeat) {
      throw new UB.UBAbortError('invalid credential')
    } else {
      return Promise.resolve({authSchema: 'UB', login: 'admin', password: 'admin'})
  onAuthorizationFail: function (reason) {
conn.then(function (conn) {
    Hello, ${conn.userLogin()}!
    We know that you are ${JSON.stringify(conn.userData())}
  conn.get('stat').then(function (statResp) {
    console.log('Current server statistics:',

  conn.Repository('ubm_navshortcut').attrs(['ID', 'code', 'caption'])
    .then(function (data) {
      console.log('First 2 adminUI shortcuts:')
      console.log(JSON.stringify(data, null, '\t'))

The same code as above will work in browser (just comment first line where XMLHttpRequest is required).



appConfigdeprecatedstatic #

Use connection.appConfig instead

connection: UBConnectionstatic #

After call to UB.connect this property will point to the active connection

i18nstatic #

Return locale-specific resource from it identifier. localeString must be:

  • either previously defined dy call to i18nExtend
  • or be a combination of entity and attribute names so that UB.i18n('uba_user') or UB.i18n('uba_role.description') would be resolved to localized entity caption or entity attribute caption


        //Localized string can be formatted either by position args:
   greeting: 'Hello {0}, welcome to {1}'
 UB.i18n('greeting', 'Mark', 'Kiev') // Hello Mark, welcome to Kiev

 //Or by named args:
   namedGreeting: 'Hello {name}, welcome to {place}'
 UB.i18n('namedGreeting', {name: 'Mark', place: 'Kiev'}) // Hello Mark, welcome to Kiev

 //Localization itself can be an object:
   loginPage: { welcome: 'Welcome to our app', user: 'Dear {user}'}
 UB.i18n('loginPage.welcome') // Welcome to our app
 UB.i18n('loginPage.user', {user: 'Pol}) // Dear Pol
 UB.i18n('loginPage') // return object {welcome: "Welcome to our app", user: "Dear {user}"}

 UB.i18n('uba_user') // -> "Users" (caption from uba_use.meta)
 UB.i18n('uba_user.firstName') // -> "First Name" (caption of uba_user.firstName attribute)
LDS_KEYSstatic #

localDataStorage keys used by @unitybase-ub-pub (in case of browser environment)

LocalDataStore: LocalDataStorestatic #

Helper class for manipulation with data, stored locally in (TubCachedData format)

MD5static #

Calculate MD5 checksum

SHA256static #

Calculate SHA256 checksum

UBAbortError: UBAbortErrorstatic #

Quiet exception. Global error handler does not show this exception for user. Use it for silently reject promise.

UBCache: UBCachestatic #

Client side cache

UBError: UBErrorstatic #

Client-side exception. Such exceptions will not be showed as unknown error in UB.showErrorWindow

UBNativeMessage: UBNativeMessagestatic #

Class for communicate with native messages plugin content script.


apply(objectTo: Object, objectsFrom: Object)→Objectstatic#

Copies all the properties of one or several objectsFrom to the specified objectTo. Non-simple type copied by reference!


returns objectTo

Arguments info:

  • objectTo: Object

    The receiver of the properties

  • objectsFrom: Object

    The source(s) of the properties

base64FromAny(data: File)→Promise<string>static#

Fast async transformation of data to base64 string


resolved to data converted to base64 string

base64toArrayBuffer(base64: String)→ArrayBufferstatic#

Convert base64 encoded string to decoded array buffer

booleanParse(v)→Boolean | nullstatic#

Convert UnityBase server Boolean response (0 or 1) to JS Boolean (false or true)

Arguments info:

  • v:

    Value to convert


Create authorized connection to UnityBase server.

For a browser clients in case value of silenceKerberosLogin localStorage key is 'true' and 'Negotiate' authorization method is enable for application will try to authenticate user using Kerberos/NTLM method.

Preferred locale tip: to define connection preferredLocale parameter call localStorage.setItem(UB.LDS_KEYS.PREFERRED_LOCALE, 'uk') before call to UBConnection.connect

Arguments info:

  • cfg:
    • host: string

      Server host

    • path: string

      API path - the same as in Server config httpServer.path

    • onCredentialRequired:

      Callback for requesting a user credentials. See UBConnection constructor requestAuthParams parameter description

    • allowSessionPersistent: boolean

      For a non-SPA browser client allow to persist a Session in the local storage between reloading of pages. In case user logged out by server side this type persistent not work and UBConnection will call onCredentialRequired handler, so user will be prompted for credentials

    • onAuthorizationFail:

      Callback for authorization failure. See event:authorizationFail event. Should handle all errors inside!

    • onAuthorized:

      Callback for authorization success. See event:authorized event.

    • onNeedChangePassword:

      Callback for a password expiration. See event:passwordExpired event

    • onGotApplicationConfig:

      Called just after application configuration retrieved from server. Accept one parameter - connection: UBConnection Usually on this stage application inject some scripts required for authentication (locales, cryptography etc). Should return a promise then done

    • onGotApplicationDomain:


        const UB = require('@unitybase/ub-pub')
let conn = UB.connect({
  host: window.location.origin,
  path: window.location.pathname,
  onCredentialRequired: function(conn, isRepeat){
      if (isRepeat){
          throw new UB.UBAbortError('invalid credential')
      } else {
          return Promise.resolve({authSchema: 'UB', login: 'admin', password: 'admin'})
  onAuthorizationFail:  function(reason){
    document.getElementById('ubstat').innerText = JSON.stringify(, null, '\t')

  conn.Repository('ubm_navshortcut').attrs(['ID', 'code', 'caption']).selectAsArray().then(function(data){
    let tmpl = _.template(document.getElementById('repo-template').innerHTML);
    let result = tmpl(data.resultData);
    // document.getElementById('ubnav').innerText = JSON.stringify(data.resultData);
    document.getElementById('ubnav').innerHTML = result;
format(stringToFormat: String, values: *)→Stringstatic#

Allows to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each token must be unique, and must increment in the format {0}, {1}, etc. Example usage:

var s = UB.format('{1}/ext-lang-{0}.js', 'en', 'locale');
// s now contains the string: ''locale/ext-lang-en.js''


The formatted string.

Arguments info:

  • stringToFormat: String

    The string to be formatted.

  • values: *

    The values to replace tokens {0}, {1}, etc in order.

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

Shortcut for xhr to perform a GET request.


Future object

Arguments info:

  • url: string

    Relative or absolute URL specifying the destination of the request

  • config: Object

    Optional configuration object as in UB.xhr

i18nExtend(localizationObject: Object)static#

Merge localizationObject to UB.i18n. Usually called form modelFolder/locale/lang-*.js scripts

inject(url: String, charsetopt: String)→Promisestatic#

Inject external script or css to DOM and return a promise to be resolved when script is loaded.

if script successfully loaded using inject it will not be loaded anymore with repeatable calls to UB.inject.

Arguments info:

  • url: String

    either js or css resource to load


        //Load script.js:

//Load several script at once and error handling:
Promise.all([UB.inject('jslibs/script.js'), UB.inject('script2.js')])
 console.log('Oh! error occurred: ' + err)

//Load one script and then load other
 console.log('first script loaded. Continue to load second')
 return UB.inject('jslibs/js_beautify1.js')

//Load couple of resources:
Promise.all([UB.inject('css/first.css'), UB.inject('css/second.css')])

Convert UnityBase server dateTime response (ISO8601 string) to Date object

Arguments info:

  • value:

    String representation of Date in ISO8601 format


Convert UnityBase server date response to Date object. date response is a day with 00 time (2015-07-17T00:00Z), to get a real date we must add current timezone shift

ns(namespacePath: String)→Objectstatic#

Creates namespaces to be used for scoping variables and classes so that they are not global.


The namespace object.



    DOC.Report.myReport = function() { ... };
post(url: string, data: *, configopt: Object)→Promisestatic#

Shortcut for xhr to perform a POST request.


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 UB.xhr

Repository(entityCode: String)→ClientRepositorystatic#

Create a new instance of repository for a current connection. To be used after connection is created.

Arguments info:

  • entityCode: String

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

setErrorReporter(errorReportedFunction: function)static#

Set a error reported callback for unhandled errors (including unhandled promise rejections). Callback signature function({errMsg, errCode, entityCode, detail})

  • errMsg is already translated using UB.i18n

This callback also called inside UBPub.showErrorWindow

showErrorWindow(errMsg: String, errCodeopt: String, entityCodeopt: String, detailopt: String)static#

Default error reported handler. Will translate error message using i18n.

For a UI other then adminUI developer can call UB.setErrorReporter to set his own error reporter

Arguments info:


        const UB = require('@unitybase/ub-pub')
      const vm = new Vue({
        methods: {
          showError: function(errMsg, errCode, entityCode, detail) {
              showClose: true,
              message: errMsg,
              type: 'error'
xhr(requestConfig: Object)→Promisestatic#

An asynchronous HTTP request. Returns a {Promise} object with the standard Promise methods (reference). The then method takes two arguments a success and an error callback which will be called with a response object. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions. Default transform check response content-type is application/json and if so - convert data to Object
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.

Arguments info:

  • requestConfig: Object
    • url: String

      Absolute or relative URL of the resource that is being requested

    • method: String

      HTTP method (e.g. 'GET', 'POST', etc). Default is GET

    • params: Object<(string|Object)>

      Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified

    • data: String

      Data to be sent as the request message data

    • headers: Object

      Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Merged with UB.xhrDefaults.headers

    • transformRequest: function

      Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.

    • transformResponse: function

      Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.

    • timeout: Number

      timeout in milliseconds, or {Promise} that should abort the request when resolved. Default to {UB.xhrDefaults.timeout}

    • withCredentials: Boolean

      whether to to set the withCredentials flag on the XHR object. See requests with credentials for more information.

    • responseType: String

      see responseType.

    • onProgress: function

      XHR onProgress callback, see ProgressEvent for details. To be user instead obsolete Q Promise.progress()

    Object describing the request to be made and how it should be processed. The object has following properties:


        //Get some data from server:
UB.xhr({url: 'getAppInfo'}).then(function(resp) {
  console.log('this is appInfo: %o',

//The same, but in more short form via {@link get UB.get} shorthand:
UB.get('getAppInfo').then(function(resp) {
  console.log('this is appInfo: %o',

//Run POST method:'ubql', [
  {entity: 'uba_user', method: 'select', fieldList: ['*']}
]).then(function(resp) {
}, function(resp) {
  console.log('request failed with status' + resp.status);

//retrieve binary data as ArrayBuffer
UB.get('downloads/cert/ACSK(old).cer', {responseType: 'arraybuffer'})
 console.log('Got Arrray of %d length',;

Intercept all unhandled errors including Promise unhandled rejections. Errors will be parsed and passed to UB.showErrorWindow {@see setErrorReporter setErrorReporter}