app

module:app

Description:
  • The primary application module containing all config options and common functions

Properties:
Name Type Description
version string

Application name/version from package.json or manually set

config string

Config file to load on startup, defaults to bkjs.conf

runMode string

Environment mode of the process or the application

packages object

Loaded packages

role string

the primary proccess role, one of: node, watcher, server, web, worker

home string

home folder, from config or env.BKJS_HOME

cwd string

always current directory on start

ipaddr string

host IP address, non-local interface

isPrimary boolean

is true if the process is primary

isWorker boolean

is true if the process is a worker process

isMainThread boolean

Is true if this code is not running inside of a Worker thread.

instance object

Current instance or container attributes gathered by other modules

Properties
Name Type Description
type string

"aws" for AWS

image string

EC2 image id

container string

ECS container name

container_id string

ECS container id

task_id string

ECS container task id

ip string

EC2/ECS private IP address

tag string

Instance/container tag set manually or derived from AWS tags

roles string

Additional roles to use for configuration purposes

worker_id string

set from cluster.worker_id

region string

AWS region

zone string

AWS availability zone

Members

(inner) args :Array.<ConfigOptions>

Type:

Methods

(static) addModule(any)

Description:
  • Adds reference to the objects in the core for further access. This is used in the core to register all internal modules and makes it available in the shell and in the module:modules object.

    If module name starts with underscore it is silently ignored. Empty names are not allowed and reported.

    Module name can contain dots, meaning to place the module under hierarchy of namespaces. Modules can be placed under existing modules, the context is still separate for each module.

    Also this is used when creating modular backend application by separating the logic into different modules, by registering such modules with the core it makes the module a first class citizen in the backendjs core and exposes all the callbacks and methods.

Parameters:
Name Type Description
any Array.<object>

modules to add

Examples
const { modules } = require("backendjs");
 const mymod = { name: "billing.invoices", request: () => { ... } }
 app.addModule(mymod);

 modules.billing.invoices.request({ ... });

The module below will register API routes and some methods

 const { api, core } = require("backendjs");
 const mymod = { name: "mymod" }
 exports.module = mymod;
 app.addModule(mymod);

 mymod.configureWeb = function(options, callback) {
    api.app.all("/mymod", (req, res) => {
         res.json({});
    });
 }
In the main app.js just load it and the rest will be done automatically, i.e. routes will be created ...

      const mymod = require("./mymod.js");

Running the shell will make the object `mymod` available

      ./app.sh -shell
      > mymod
        { name: "mymod" }

(static) ainit()

Description:
  • Async version of app.init

(static) arunMethods()

Description:
  • async/await version of runMethods

(static) checkConfig(callbackopt) → {none}

Description:
  • Reload runtime config from the DB

Parameters:
Name Type Attributes Description
callback function <optional>

a function to call after the check

Returns:
Type Description
none

(static) createRepl()

Description:
  • Create REPL interface with all modules available

(static) describeArgs(args) → {object}

Description:
  • Add custom config parameters to be understood and processed by the config parser

Parameters:
Name Type Description
string

a module name to add these params to

args Array.<object>

a list of objects in the format: { name: N, type: T, descr: D, min: M, max: M, array: B... }, all except name are optional.

Returns:
Type Description
object

a module object where args added or undefined if not

Example
app.describeArgs("api", [ { name: "num", type: "int", descr: "int param" }, { name: "list", array: 1, descr: "list of words" } ]);
app.describeArgs("app", [ { name: "list", array: 1, descr: "list of words" } ]);

(static) init(options, callbackopt)

Description:
  • Main initialization, must be called prior to perform any actions.

Parameters:
Name Type Attributes Description
options object

options for customization what to init

Properties
Name Type Attributes Description
role boolean <optional>

set the process role

roles boolean <optional>

set the instance config roles

nodb boolean <optional>

if true do not initialize database

nodbconf boolean <optional>

if true do not read remote config database

noconfigure boolean <optional>

do not run all configure methods

nomodules boolean <optional>

do not load modules

nopackages boolean <optional>

do not load npm packages

callback function <optional>

called at the end with possible err

(static) isOk(name, optionsopt)

Description:
  • Return true if the given service is not disabled and no property no${name} exists in the options

Parameters:
Name Type Attributes Description
name string

service name

options object <optional>

(static) killBackend()

Description:
  • Kill all backend processes that match name and not the current process

(static) loadModules(dir, includeopt, excludeopt) → {Array.<string>}

Description:
  • Dynamically load services from the specified directory.

    The modules are loaded using require as a normal nodejs module but in addition if the module exports init method it is called immediately with options passed as an argument. This is a synchronous function so it is supposed to be called on startup, not dynamically during a request processing.

    Only .js files from top level are loaded by default unless the depth is provided. addModule is called automatically, it uses findFileSync to locate the modules, options depth, include or exclude` can be provided

    Each module is put in the top level modules registry by name, the name can be a property name or the module base file name. Module names starting with underscore will not be added to the registry.

    If a module name contains dots it means nested hierarchy, all intermediate objects will be created automatically. Nested names allow a better separation of modules and name collisions.

    Caution must be taken for module naming, it is possible to override any default bkjs module which will result in unexpected behaviour

    The following module properties are reserved and used by the backendjs:

    • name - module name
    • deps - dependent module name be placed after, -M to be placed before, a single - means place at the beginning
    • args - list of config parameters
    • tables - table definitions
Parameters:
Name Type Attributes Description
dir string

name of directory containing modules

options.depth number <optional>

how deep to look for modules

include regexp <optional>

regexp to match files or paths to load, default is .js

exclude regexp <optional>

regexp what files or paths to exlude

Returns:
Type Description
Array.<string>

a list of all loaded module names

Example
// load all modules from the local relative directory
 app.loadModules("modules")

(static) loadPackages(list, options) → {String}

Description:
  • Load NPM packages and auto configure paths from each package. bkjs.conf in the root of the package will be loaded as a config file.

Parameters:
Name Type Description
list String | Array

list of packages to load

options Object

an object with optional parameters

Returns:
Type Description
String

all config files for all packages concatenated

(static) mime()

Description:
  • Expose mime via core, compatibility with mime module, Express uses it anyway so our dependency is justified and reusing the same module

Properties:
Name Type Description
mime object

mime module

(static) parseArgs(argv, pass, fileopt)

Description:
  • Parse command line arguments

Parameters:
Name Type Attributes Description
argv Array.<string>

a list of config parameters in the form [ "-param", "value" ,...]

pass int

a number representing a pass phase

file string <optional>

file name where parameters came from

(static) parseConfig(data, pass, fileopt)

Description:
  • Parse config lines for the file or other place,

Parameters:
Name Type Attributes Description
data string

data from a config file

pass int

a number representing a pass phase

file string <optional>

file name where parameters came from

(static) processArg(options)

Description:
  • Process a single argument

Parameters:
Name Type Description
options object

are supposed to be returned by _findArg or prepared accordingly

(static) processArgs(mod, argv, pass, fileopt)

Parameters:
Name Type Attributes Description
mod object

run for module's args only

argv Array.<string>

a list of config parameters in the form [ "-param", "value" ,...]

pass int

a number representing a pass phase

file string <optional>

file name where parameters came from

(static) processEnvArgs()

Description:
  • Process parameters from env variables

(static) processName() → {string}

Description:
  • Return unique process name based on the cluster status, worker or server and the role. This is can be reused by other workers within the role thus making it usable for repeating environments or storage solutions.

Returns:
Type Description
string
  • process name

(static) runMethod(mod, name, params, options, callbackopt) → {undefined}

Description:
  • Run a method for the given module

Parameters:
Name Type Attributes Description
mod string

module name

name string

method name

params object

parameters for the method

options object

additional options to control method execution

Properties
Name Type Attributes Description
logger_allow array <optional>

list of properties to be logged only on error instead of params

logger_error string <optional>

logger level for error reporting

stopOnError boolean <optional>

if true return an error in the callback to stop processing other methods

stopFilter function <optional>

a function that must return true in order to stop execution other methods

callback function <optional>

function to be called at the end

Returns:
Type Description
undefined

(static) runMethods(name, params, options, allow)

Description:
  • Run a method for every module, a method must conform to the following signature: function(options, callback) and call the callback when finished. The callback second argument will be the parameters passed to each method, the options if provided can specify the conditions or parameters which wil be used by the `runMethods`` only.

    The modules's deps property defines the position in the modules list and thus determines the order of calling methods. The property contains other module name this module depend on, i.e. it must be placed after it. if deps starts with - it means place this module before the other module. A single - means place it at the beginningh of the list.

Parameters:
Name Type Description
name string

method name

params object

parameters for the method

options object

additional options to control method execution

Properties
Name Type Attributes Description
logger_allow array <optional>

list of properties to be logged only on error instead of params

logger_error string <optional>

logger level for error reporting

stopOnError boolean <optional>

if true return an error in the callback to stop processing other methods

stopFilter function <optional>

a function that must return true in order to stop execution other methods

allow regexp

regexp with allowed modules, in options only

regexp

allowModules - a regexp of the modules names to be called only

boolean

stopOnError - on first error stop and return, otherwise all errors are ignored and all modules are processed

function

stopFilter - a function to be called after each pass to check if the processing must be stopped, it must return true to stop

string

logger_error - logger level, if not specified an error with status 200 will be reported with log level 'info' and other errors with level 'error'

object

logger_inspect - an object with inspect options to override current inspect parameters

array

logger_allow - a list of properties allowed in the log on error, this is to prevent logging too much or sensitive data

boolean

parallel - if true run methods for all modules in parallel using lib.forEach

number

concurrency - if a number greater than 1 run that many methods in parallel using lib.forEachLimit

boolean

sync - if true treat methods as simple functions without callbacks, methods MUST NOT call the second callback argument but simply return

boolean

direct - if true call all methods directly otherwise via setImmediate

(static) setHome(home)

Description:
  • Switch to new home directory, exit if we cannot, this is important for relative paths to work if used, no need to do this in worker because we already switched to home directory in the server and all child processes inherit current directory Important note: If run with combined server or as a daemon then this MUST be an absolute path, otherwise calling it in the spawned web server will fail due to the fact that we already set the home and relative path will not work after that.

Parameters:
Name Type Description
home string

new home directory to chdir

(static) setHost(hostopt) → {string}

Description:
  • Set hostname and domain name

Parameters:
Name Type Attributes Description
host string <optional>

new host name to set

Returns:
Type Description
string
  • current host name

(static) setLogInspect()

Description:
  • Install internal inspector for the logger, an alternative to the util.inspect

(static) setRole()

Description:
  • Set process and logger role

(static) sortModules()

Description:
  • Sort modules according to dependencies in deps property.

(static) start(options, shell, watch, nowatch, server, noserver, api, worker)

Description:
  • Start the application, runs app.init before switching to the requested role. The options can be used to set the role instead of command line args: shell, server, watch, api, worker

Parameters:
Name Type Description
options object

properties to customize initialization

shell boolean

run the shell process

watch boolean

run the watcher process

nowatch boolean

ignore watcher mode

server boolean

run the main server process with api workers

noserver boolean

ignore server mode

api boolean

run the standalone api process

worker boolean

run the standalone worker process

(static) startRepl()

Description:
  • Start command prompt on TCP socket, context can be an object with properties assigned with additional object to be accessible in the shell

(static) stop()

Description:
  • Shutdown all services, calls the shutdown method first and then shutdownRole method.

(static) watchTmp()

Description:
  • Watch temp files and remove files that are older than given number of seconds since now, remove only files that match pattern if given Options properties:

    • path - root folder, relative or absolute
    • age - number of seconds a file to be older to be deleted, default 1 day
    • include - a regexp that specifies only files to be watched
    • exclude - a regexp of files to be ignored
    • nodirs - if 1 skip deleting directories
    • depth - how deep to go, default is 1