new App()#
Mixes In:

Singleton instance of UnityBase application. Allow direct access to the database connections, blob stores, HTTP endpoints (full control on HTTP request & response) registration, read domain and server config.

Mixes EventEmitter, and server will emit:

  • endpointName + ':before' event before endpoint handler execution
  • endpointName + ':after' event in case neither exception is raised nor App.preventDefault() is called inside endpoint handler
 const App = require('@unitybase/ub').App
 // Register public (accessible without authentication) endpoint
 App.registerEndpoint('echoToFile', echoToFile, false)

 // write custom request body to file FIXTURES/req and echo file back to client
 // @param {THTTPRequest} req
 // @param {THTTPResponse} resp
 function echoToFile (req, resp) {
   var fs = require('fs')
   fs.writeFileSync(path.join(FIXTURES, 'req'), req.read('bin'))
   resp.statusCode = 200
   resp.writeEnd(fs.readFileSync(path.join(FIXTURES, 'req'), {encoding: 'bin'}))
 }

 //Before getDocument requests
 //@param {THTTPRequest} req
 //@param {THTTPResponse} resp
 function doSomethingBeforeGetDocumentCall(req, resp){
   console.log('User with ID', Session.userID, 'try to get document')
 }
 // Adds hook called before each call to getDocument endpoint
 App.on('getDocument:before', doSomethingBeforeGetDocumentCall)

 const querystring = require('querystring')
 //
 //After getDocument requests
 //@param {THTTPRequest} req
 //@param {THTTPResponse} resp
 function doSomethingAfterGetDocumentCall(req, resp){
   params = querystring.parse(req.parameters)
   console.log('User with ID', Session.userID, 'obtain document using params',  params)
 }
 App.on('getDocument:after', doSomethingAfterGetDocumentCall)

To prevent endpoint handler execution App.preventDefault() can be used inside :before handler.

Members

blobStoresstatic #

BLOB stores methods. Usage:

dbConnections: Object<string, DBConnection>static #

Databases connections

defaultLang: Stringstatic #

Application default language

domainInfo: UBDomainstatic #

Extended information about application domain (metadata)

emitterEnabled: Booleandeprecatedstatic #

Is event emitter enabled for App singleton. Default is false

Starting from 1.11 this property ignored (always TRUE)

externalURL: Stringstatic #

URL that the User from the internet will use to access your server. To be used in case server is behind a reverse proxy

localIPsstatic #

List of a local server IP addresses CRLF (or CR for non-windows) separated

package: Objectstatic #

Application package.json content (parsed)

serverConfig: Objectstatic #

Server configuration - result of argv.getServerConfiguration

Name Type Description
httpServer Object

HTTP server config

application Object
application.name string
application.defaultLang string
application.domain Object
application.domain.models Array
application.domain.supportedLanguages Array<string>
application.customSettings Object
uiSettings Object

Section uiSettings of ubConfig

security Object
serverPublicCert: stringstatic #

Defense edition only, Base64 encoded public server certificate

Contains non empty value in case security.dstu.trafficEncryption === true and key name defined in security.dstu.novaLib.keyName

serverURL: Stringstatic #

Full URl HTTP server is listen on (if HTTP server enabled, else - empty string)

staticPath: Stringstatic #

Full path to application static folder if any, '' if static folder not set

Methods

addAppLevelMethod()staticdeprecated#

authFromRequest(noHTTPBodyInResp: boolean, doSetOutCookie: boolean)→Booleanstatic#

Try retrieve or create new session from request headers. Return true if success, false if more auth handshakes is required. In case of invalid credential throw security exception.

Arguments info:

  • noHTTPBodyInResp: boolean

    If true do not write a uData to the HTTP response

  • doSetOutCookie: boolean

    If true set a out authorization cookie on success response (Negotiate only)

dbCommit(connectionNameopt: String)→Booleanstatic#

Commit active database transaction if any. In case connectionName is not passed will commit all active transactions for all connections. Return true if transaction is committed, or false if database not in use or no active transaction.

dbInTransaction(connectionName: String)→Booleanstatic#

Check database are used in current endpoint context and DB transaction is already active.

dbRollback(connectionNameopt: String)→Booleanstatic#

Rollback active database transaction if any. In case connectionName is not passed will rollback all active transactions for all connections. Return true if transaction is rollback'ed, or false if database not in use or no active transaction.

dbStartTransaction(connectionName: String)→Booleanstatic#

Start a transaction for a specified database. If database is not used in this context will create a connection to the database and start transaction.

For Oracle with DBLink first statement to DBLink'ed table must be either update/insert/delete or you MUST manually start transaction to prevent "ORA-01453: SET TRANSACTION be first statement"

deleteFromFTSIndex(entityName: String, instanceID: Number)static#

Delete row from FTS index for exemplar with instanceID of entity entityName (mixin fts must be enabled for entity)

els(entityCode: String, methodCode: String)→booleanstatic#

Check Entity-Level-Security for specified entity/method

 if App.els('uba_user', 'insert'){
     // do something
 }

fileChecksum(pathToFile: String)→stringstatic#

First check in global cache for a entry "UB_GLOBAL_CACHE_CHECKSUM + filePath" and if not exists - calculate a checksum using algorithm defined in CONTROLLER.serverConfig.HTTPServer.watchFileChanges.hashingStrategy if server in dev mode always return current timestamp values from cache will be cleared in directoryNotifiers

folderChecksum(pathToFolder: string)→stringstatic#

A folder checksum (see fileChecksum for algorithm details)

getUISettings()→stringstaticdeprecated#

Use App.serverConfig.uiSettings: Object instead

Return stringified JSON specified in serverConfig.uiSettings

globalCacheGet(key: String)→Stringstatic#

Get value from global cache. Global cache shared between all threads.

Return '' (empty string) in case key not present in cache.

Arguments info:

globalCachePut(key: String, value: String)static#

Put value to global cache.

Arguments info:

  • key: String

    Key to put into

  • value: String

    Value to put into this key. If === null then key will be remover from cache

logout()static#

Logout (kill stored Sessions) current session user

logoutAllWithTheSameNameExceptMe()static#

Logout (kill stored Sessions) all users with the same as currently logged (except currently logged user)

preventDefault()static#

Accessible inside app-level :before event handler. Call to prevent default method handler. In this case developer are responsible to fill response object, otherwise HTTP 400 is returned.

registerEndpoint(endpointName: String, handler: function, authorizationRequiredopt: boolean, isDefaultopt: boolean)static#

Register a server endpoint. One of the endpoints can be default endpoint - it will be used as a fallback in case URL do not start with any of known endpoints name.

Exceptions inside endpoint handler are intercepted by UB server. In case exception is occurred server will rollback any active DB transactions and serialize an exception message to response depending on server execution mode:

  • for dev mode - original exception text will be serialized (for debugging purpose)
  • for production mode - in case exception message is wrapped into <<<..>>> then this message will be serialized, if not - text will be always Internal server error (for security reason)

    Recommended way to throw an handled error inside endpoint handler is throw new UB.UBAbort('.....')

Arguments info:

  • authorizationRequired = true : boolean

    If true UB will check for valid Authorization header before execute endpoint handler

Examples

    
        // Write a custom request body to file FIXTURES/req and echo file back to client
 // @param {THTTPRequest} req
 // @param {THTTPResponse} resp
 //
 function echoToFile(req, resp) {
   var fs = require('fs');
   fs.writeFileSync(FIXTURES + 'req', req.read('bin'));
   resp.statusCode = 200;
   resp.writeEnd(fs.readFileSync(FIXTURES + 'req', {encoding: 'bin'}));
 }
 App.registerEndpoint('echoToFile', echoToFile);
    
resolveStatic(aRequestedFile: String)→Stringstatic#

Resolve aRequestedFile to real file path. Internally analyse request and if it start with model/ - resolve it to model public folder else - to inetPub folder. Will return '' in case of error (filePath not under inetPub or model/) to prevent ../../ attack

updateFTSIndex(entityName: String, instanceID: Number)static#

Update FTS index for for exemplar with instanceID of entity entityName (mixin fts must be enabled for entity). In case row dose not exist in FTS perform insert action automatically.