Core

Server.Modules. Core

# new Core()

This is the Core Module of the Blackrock Application Server. It is responsible for loading all remaining modules and interfaces within Blackrock. This module exports the core object (an instantiated version of the Core class contained within) to the parent Server namespace. You do not need to instantiate this module's class (by calling the constructor), as this is done automatically for you.

Author:
  • Darren Smith
License:
  • Licensed under the LGPL license.
Examples
// Get Core Object (Calling Blackrock As A Dependency):
require('is-blackrock').init()
  .then(function(core) {
    const log = core.module('logger).log;
    log('debug', 'My App - The Status of Core is ' + core.status, {}, 'CORE_STATUS');
    // Output: 'The Status of Core is Active' (if server has finished initialising)
  });
// Get Core Object (From App Controller):
const ctrl = function() {};
ctrl.get = function(req, res) {
  const log = req.core.module('logger).log;
  log('debug', 'My App - The Status of Core is ' + core.status, {}, 'CORE_STATUS');
  // Output: 'The Status of Core is Active' (if server has finished initialising)
}

Extends

Classes

Base
CoreProxy
Interface
Module

Members

# (static) globals

This object contains methods to get and set methods that are globally accessible across the Application Server. It does NOT need to be instantiated and can/should not be called directly. You can read more about the get method here - Server.Modules.Core#globals.get. And the set method here - Server.Modules.Core#globals.set

Properties
Name Type Description
globals.set function

Sets global variable value

globals.get function

Gets global variable value

Examples
// Set a global variable:
core.globals.set('test', 'value');     // Returns: true
// Get a global variable:
core.globals.get('test');              // Returns: 'value'

Methods

# (static) cfg() → {object}

This method can be accessed when calling Blackrock As A Dependency, and also from within the app controllers (if enabled in config: config['app-engine'].allow.cfg = true). It returns the application server's current configuration state. This state, of course, is originally read from the config file on the filesystem when the application server starts up. And can also be passed through or modified via the Init Object (the first parameter that you pass to Blackrock's Init Method.

Properties
Name Type Description
cfg.update function

Updates the Configuration

Returns:

config - The Config Object. See Server Configuration

Type
object
Examples
// Return Application Server Configuration Object (Calling Blackrock As A Dependency):
const initObject = { config: amendedConfigData}
require('is-blackrock').init(initObject)
  .then(function(core) {
    const log = req.core.module('logger').log;
    const config = core.cfg();
    log('debug', 'My App > Message - ' + config.core.banner, {}, 'MY_APP_SENDING_CONFIG_BANNER');
    // Output: 'Blackrock Application Server (Default)' (In Console)
  });
// Updates the live configuration of the application server:
require('is-blackrock').init()
  .then(function(core) {
    const result = core.cfg.update({'test': 'value'});
    if(result) console.log('Updated');
    else console.log('Update Failed');
  });

# (static) fetchBasePath(type) → {string}

This method can be used when accessing core where Blackrock is a dependency of your own project, and can also be used from within a app controller (where enabled in config). It fetches whichever base path type you specify by name when calling it. Options include - 'apps', 'module', 'config', 'cache', 'root'.

Parameters:
Name Type Description
type string

The Base Path Type

Returns:

basePath - The Requested Base Path

Type
string
Examples
// Return Application Server Configuration Object (Calling Blackrock As A Dependency):
require('is-blackrock').init()
  .then(function(core) {
    const log = core.module('logger).log;
    const appBasePath = core.fetchBasePath('apps');
    log('debug', 'My App > App Base Path Is ' + appBasePath, {}, 'MY_APP_BASE_PATH');
    // Output: 'App Base Path Is /home/alice/my-local-swarm/apps' (In Console)
  });
// Return Application Server Configuration Object (From App Controller. In - Say, a Stand-Alone Setup):
const ctrl = function() {};
ctrl.get = function(req, res) {
  const log = req.core.module('logger).log;
  const appBasePath = req.core.fetchBasePath('apps');
  log('debug', 'My App > App Base Path Is ' + appBasePath, {}, 'MY_APP_BASE_PATH');
  // Output: 'App Base Path Is /opt/blackrock/apps' (In Console, Stand-Alone Application Server Mode)
}

# (static) getCoreProxy(myConfig, app) → {Server.Modules.Core.CoreProxy}

This method provides an instance of the CoreProxy Class that acts as a proxy between the Core Module Singleton and app code, to ensure that the app only has limited access to the methods contained within the Core Module This includes limited access to modules that are accessible via the child module() method and apps. The method names defines within the myConfig[module] array can take one of three forms - a plain method name (eg; "log"), a nested method name (eg; "csv.parse") or a method name with a constraint placed on the input parameter (eg; "app(appName)").

Parameters:
Name Type Description
myConfig object

Configuration Object

Properties
Name Type Attributes Description
cfg boolean <optional>

Make the cfg() method available? True | False

pkg boolean <optional>

Make the pkg() method available? True | False

fetchBasePath boolean <optional>

Make the fetchBasePath() method available? True | False

shutdown boolean <optional>

Make the shutdown() method available? True | False

globals boolean <optional>

Make the Core Globals Singleton available? True | False

modules object

An object of modules to make available

Properties
Name Type Attributes Description
cli array <optional>

An array of method names to enable for the CLI Module

daemon array <optional>

An array of method names to enable for the Daemon Module

errorhandler array <optional>

An array of method names to enable for the ErrorHandler Module

farm array <optional>

An array of method names to enable for the Farm Module

generator array <optional>

An array of method names to enable for the Generator Module

i18n array <optional>

An array of method names to enable for the i18n Module

installer array <optional>

An array of method names to enable for the Installer Module

jobs array <optional>

An array of method names to enable for the Jobs Module

logger array <optional>

An array of method names to enable for the Logger Module

router array <optional>

An array of method names to enable for the Router Module

sandbox array <optional>

An array of method names to enable for the Sandbox Module

utilities array <optional>

An array of method names to enable for the Utilities Module

validate array <optional>

An array of method names to enable for the Validate Module

http array <optional>

An array of method names to enable for the HTTP Interface

websockets array <optional>

An array of method names to enable for the WebSockets Module

axon array <optional>

An array of method names to enable for the Axon Module

nanomsg array <optional>

An array of method names to enable for the NanoMSG Module

ssh array <optional>

An array of method names to enable for the SSH Module

zeromq array <optional>

An array of method names to enable for the ZeroMQ Module

app Server.Modules.AppEngine.App

App Instance

Returns:

coreProxyInstance - Core Proxy Instance

Type
Server.Modules.Core.CoreProxy
Example
const config = core.cfg();
const coreProxyInstance = core.getCoreProxy(config['app-engine'].allow);

# (static) init(initialConfig, callbackFn) → {Server.Modules.Core}

This method initialises the application server. It is called automatically when you are running the server in stand-alone mode. If you are running the server as a dependency for another application, then you must call this method on the object returned by require in order to start the server. The server will remain in an inactive state up until you call this method.

Parameters:
Name Type Description
initialConfig object

Initial Configuration Data

Properties
Name Type Description
silent object

True disables console logging (when embedding in your own app), Else False

test object

True enables test mode, Else False

config object

Configuration Block. See Server Configuration

callbackFn function

The Callback Function

Returns:

core - The Core Module

Type
Server.Modules.Core
Example
// Initialise the Application Server (Not Available to App Controllers):
require('is-blackrock').init()
  .then(function(core) {
    console.log(core.status);
    // Output: 'Active' (if server has finished initialising)
  });

# (static) module(name, typeopt) → {Server.Modules.Core.Module}

This method (when provided with a module name), returns the singleton for that module to the caller. Module singletons are instantiated at server startup - with this being configurable within the server config. Note: To use this method from an app controller, you must enable the modules you will have access to within the server config, along with the method names within. Eg; config['app-engine'].allow.modules[moduleName] = methodName (See Server Configuration)

Parameters:
Name Type Attributes Description
name string

Module Name

type string <optional>

Module Type (Leave blank for standard module, or enter 'interface' for an interface

Properties
Name Type Description
module.count function

Returns number of loaded modules and/or interfaces

module.load function

Loads a module and instantiates it's Singleton

module.isLoaded function

Waits until module loads and then fulfills a Promise

module.closeAll function

Closes all active modules

Returns:

module - The Requested Module

Type
Server.Modules.Core.Module
Examples
// module() - Return the Module Singleton:
const logger = core.module('logger');
logger.log('debug', 'This is a test message');
// Output: 'This is a test message' will appear in the logs (incl. console if enabled)
// module.count() - Return a Count of Loaded Modules:
const moduleCount = core.module.count('modules');
log('debug', 'My App > How many modules are loaded? It's - ' + moduleCount, {}, 'MY_APP_COUNT_DEM_MODS');
// Output: 10 (or however many modules have been loaded)
// module.load() - Loads a module:
core.module.load('module', 'logger', function(err, loggerModule){
    loggerModule.log('debug', 'My App > Hello!', {}, 'LOADED_MOD');
    // Output: "My App > Hello!"
});
// module.isLoaded() - Waits until module is loaded and then fulfills a Promise:
 core.module.isLoaded('cli').then(function IsLoadedPromiseThen(cliMod) {
   cliMod.register([
     {'cmd': 'drop-acid', 'params': 'mindset=happy', 'info': 'Takes you on a wild trip', 'fn': function (params) {
       core.emit('OH_SHIT_HE_DID_IT', {'command': 'start-trip', 'params': params});
     }},
   ]);
 }).catch(function IsLoadedPromiseFail(err) {
   log('error',
       'My App > He Failed. He's now in the psych ward',
       err, 'DROP_ACID_FAIL');
 });
// module.closeAll() - Scope is that it's being executed from within Core Module Internals
core.module.closeAll();
// Output in Logs: '20201201 00:00:00 (shutdown) All Modules Have Been Terminated'

# (static) pkg() → {object}

This method returns a Javascript object that contains the parsed content of the package.json file. If the server is running in stand-alone mode, then this will be the package.json file of the actual is-blackrock module. Otherwise, it will be the package.json file of the host application that is accessing Blackrock as a dependency.

Returns:

pkg - The Parsed Package File

Type
object
Examples
// Return Application Server's Parsed Package.json file (calling a dependency):
require('is-blackrock').init()
  .then(function(core) {
    const log = core.module('logger).log
    const pkg = core.pkg();
    log('debug', 'My App > What's in the package? It's a - ' + pkg.name, {}, 'MY_APP_THE_PACKAGE');
    // Output: "Blackrock Application Server"
  });
// Return Application Server's Parsed Package.json file (From App Controller)
const ctrl = function() {};
ctrl.get = function(req, res) {
  const log = req,core.module('logger).log
  const pkg = req.core.pkg();
  log('debug', 'My App > What's in the package? It's a - ' + pkg.name, {}, 'MY_APP_THEIR_PACKAGE');
  // Output: "Blackrock Application Server". But take note - you must enable this within the server
  // config (config['app-engine].allow.pkg = true).
}

# (static) ready(callbackFn) → {Promise}

This method waits until the server becomes Active and then executes upon a Promise, providing the Core Module / Application Server Singleton as the sole parameter within the Promise's Then function. If the server is already active it will immediately resolve the promise.

Parameters:
Name Type Description
callbackFn function

Callback Function

Returns:

promise - A Promise

Type
Promise
Example
// Check if server is ready (Only required when calling Blackrock as a dependency):
require('is-blackrock').init()
  .then(function(core) {
    core.ready().then(function(newCore) {
      const log = newCore.module('logger).log
      log('debug', 'My App > Let's get ready to rumble!!!', {}, 'MY_APP_RUMBLING_ALL_OVER_THE_SHOP');
      // Output: "My App > Let's get ready to rumble!!!" (In Console)
    });
  });

# (static) shutdown(shutdownMsg)

This method will trigger a system shutdown. It is always available from a parent application (where Blackrock has been included as a dependency). It is only available from app code (initialisation method or route handlers) if it is enabled within within the server configuration file: config['app-engine'].allow.shutdown = true

Parameters:
Name Type Description
shutdownMsg string

Shutdown Message

Example
// Shutdown the server:
require('is-blackrock').init()
  .then(function(core) {
    core.shutdown();
    // Note: The server will begin shutting down now...
  });

# (static) void()

This method does not do anything. It exists in order to provide a work-around for when some method must be called on the core application server instance, but you do not actually need the method to do anything or to return a result.

Examples
// Voiding (Calling Blackrock As A Dependency):
require('is-blackrock').init()
  .then(function(core) {
    core.void();
    // Output: Does Nothing. I mean... What did you expect?
  });
// Voiding (From App Controller):
const ctrl = function() {};
ctrl.get = function(req, res) {
  req.core.void();
  // Output: Yep. Still does nothing,
}