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) {
    console.error(reason)
  }
})
conn.then(function (conn) {
  console.log(`
    Hello, ${conn.userLogin()}!
    We know that you are ${JSON.stringify(conn.userData())}
  `)
  conn.get('stat').then(function (statResp) {
    console.log('Current server statistics:', statResp.data)
  })

  conn.Repository('ubm_navshortcut').attrs(['ID', 'code', 'caption'])
    .limit(2)
    .selectAsObject()
    .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).

Submodules

Members

appConfig deprecated static #

Use connection.appConfig instead

connection : UBConnection static #

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

i18n static #

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

LDS_KEYS static #

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

LocalDataStore : LocalDataStore static #

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

MD5 static #

Calculate MD5 checksum

SHA256 static #

Calculate SHA256 checksum

UBAbortError : UBAbortError static #

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

UBCache : UBCache static #

Client side cache

UBError : UBError static #

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

UBNativeMessage : UBNativeMessage static #

Class for communicate with native messages plugin content script.

Methods

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

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

Arguments info:

  • objectTo: Object

    The receiver of the properties

  • objectsFrom: Object

    The source(s) of the properties

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

Fast async transformation of data to base64 string

base64toArrayBuffer(base64 : String)→ArrayBuffer static #

Convert base64 encoded string to decoded array buffer

booleanParse(v)→Boolean | null static #

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

Arguments info:

  • v:

    Value to convert

connect(cfg)→<UBConnection> static #

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:

Examples

    
        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){
      alert(reason)
  }
})
conn.then(function(conn){
  conn.get('stat').then(function(statResp){
    document.getElementById('ubstat').innerText = JSON.stringify(statResp.data, 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 : *)→String static #

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

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

Shortcut for xhr to perform a GET request.

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

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

Examples

    
        //Load script.js:
UB.inject('jslibs/script.js')

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

//Load one script and then load other
UB.inject('jslibs/js_beautify.js').then(function(){
 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')])
    
iso8601Parse(value)→UBDomain.ubDataTypes.Date static #

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

Arguments info:

  • value:

    String representation of Date in ISO8601 format

iso8601ParseAsDate(value)→UBDomain.ubDataTypes.Date static #

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

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

Examples

    
        UB.ns('DOC.Report');

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

Shortcut for xhr to perform a POST request.

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)→ClientRepository static #

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:

Examples

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

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

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

Examples

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

//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', resp.data)
})

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

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

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