Base provides advanced Promise Queue Manager, Custom Console Logger and other utilities.

Overview

Base

npm version

Base provides frequently used functionality like cutome logger, response helper, Custom Promise and Instance composer. These are used in almost all PLG Works repositories and hence the name Base.

Installation

npm install @plgworks/base --save

Logger

Logging is a basic functionality which is needed in all the applications. Custom logger helps in standardizing the logging and thus help in debugging and analysis. To log different levels of information, we use different colors, which can be visually distinguished easily.

In the following snippet, we try to showcase all the logger methods with documentation in comments.

const Base = require('@plgworks/base');
const Logger  = Base.Logger;

// Constructor's first parameter is the module name. This is logged in every line to separate logs from multiple modules.
// Constructor's second parameter is the log level. Depending on log level, some methods will work and others will not do anything.
const logger  = new Logger("<module name>", Logger.LOG_LEVELS.TRACE);

//Log Level FATAL 
logger.notify("notify called");

//Log Level ERROR
logger.error("error called");

//Log Level WARN
logger.warn("warn called");

//Log Level INFO
logger.info("info Invoked");
logger.step("step Invoked");
logger.win("win called");

//Log Level DEBUG
logger.log("log called");
logger.debug("debug called");
logger.dir({ l1: { l2 : { l3Val: "val3", l3: { l4Val: { val: "val"  }}} }});

//Log Level TRACE
logger.trace("trace called");

All methods will be available for use irrespective of configured log level. Log Level only controls what needs to be logged.

Method to Log Level Map

| Method | Enabling |

Log Level
notify FATAL
error ERROR
warn WARN
info INFO
step INFO
win INFO
debug DEBUG
log DEBUG
dir DEBUG
trace TRACE

Response formatter

Response formatter helps to maintain standard format of the response given out by various libraries and services.

// rootPrefix is the path to the root of this package. Give proper path if installed inside node_modules
const rootPrefix = '.';

// paramErrorConfig is an object with error identifiers as key and value is an object with keys parameter and message.
// parameter is the name of the parameter which had error, for example invalid value, missing value, etc.
const paramErrorConfig = require(rootPrefix + '/tests/mocha/lib/formatter/paramErrorConfig');

// apiErrorConfig is an object with error identifiers as key and value is an object with keys http_code, code and message.
// http_code goes as the api http code while rendering.
// message and code goes in the error object.
const apiErrorConfig = require(rootPrefix + '/tests/mocha/lib/formatter/apiErrorConfig');

const Base = require('@plgworks/base');
const ResponseHelper  = Base.responseHelper;

// Creating an object of ResponseHelper. Parameter is an object with key moduleName.
const responseHelper = new ResponseHelper({
      moduleName: '<module name>'
  });
    
// for sending an error which is not parameter specific, following function can be used.
// internal_error_identifier is used for debugging.
// api_error_identifier is used to fetch information from the apiErrorConfig
const r1 = responseHelper.error({
  internal_error_identifier: 's_vt_1', 
  api_error_identifier: 'test_1',
  debug_options: {id: 1234},
  error_config: {
    param_error_config: paramErrorConfig,
    api_error_config: apiErrorConfig   
  }
});

// r1.toHash() gives following:
// {
//   success: false,
//   err: {
//     code: 'invalid_request',
//     msg: 'At least one parameter is invalid or missing. See err.error_data for more details.',
//     error_data: [],
//     internal_id: 's_vt_1'
//   }
// }
    
// For sending parameter specific errors, following function can be used.
// internal_error_identifier is used for debugging.
// api_error_identifier is used to fetch information from the apiErrorConfig
// params_error_identifiers is array of string, which are keys of paramErrorConfig
const r2 = responseHelper.paramValidationError({
  internal_error_identifier:"s_vt_2", 
  api_error_identifier: "test_1", // key of apiErrorConfig
  params_error_identifiers: ["test_1"], // keys of paramErrorConfig
  debug_options: {id: 1234},
  error_config: {
    param_error_config: paramErrorConfig,
    api_error_config: apiErrorConfig   
  }
});

// r2.toHash() gives following:
// {
//   success: false,
//   err: {
//     code: 'invalid_request',
//     msg: 'At least one parameter is invalid or missing. See err.error_data for more details.',
//     error_data: [  { parameter: 'Username', msg: 'Invalid' } ],
//     internal_id: 's_vt_2'
//   }
// }

// To check if the Result object is a success or not isSuccess function can be used. It returns a boolean.
// For example:
r1.isSuccess(); // this will be false.

// isFailure function return NOT of that returned by isSuccess function.
// For example:
r1.isFailure(); // this will be true.

// To convert to a format which can be exposed over API, toHash function can be used.
r1.toHash(); // Examples given above.

CustomPromise QueueManager

QueueManager provides various management options and configurations for a queue of Promises. Following is a brief documentation of the various manager options and example usage.

const Base = require('@plgworks/base'),
  logger  = new Base.Logger("my_module_name");

const queueManagerOptions = {
  // Specify the name for easy identification in logs.
  name: "my_module_name_promise_queue"

  // resolvePromiseOnTimeout :: set this flag to false if you need custom handling.
  // By Default, the manager will neither resolve nor reject the Promise on time out.
  , resolvePromiseOnTimeout: false
  // The value to be passed to resolve when the Promise has timedout.
  , resolvedValueOnTimeout: null

  // rejectPromiseOnTimeout :: set this flag to true if you need custom handling.
  , rejectPromiseOnTimeout : false

  //  Pass timeoutInMilliSecs in options to set the timeout.
  //  If less than or equal to zero, timeout will not be observed.
  , timeoutInMilliSecs: 5000

  //  Pass maxZombieCount in options to set the max acceptable zombie count.
  //  When this zombie promise count reaches this limit, onMaxZombieCountReached will be triggered.
  //  If less than or equal to zero, onMaxZombieCountReached callback will not triggered.
  , maxZombieCount: 0

  //  Pass logInfoTimeInterval in options to log queue healthcheck information.
  //  If less than or equal to zero, healthcheck will not be logged.
  , logInfoTimeInterval : 0


  , onPromiseResolved: function ( resolvedValue, promiseContext ) {
    //onPromiseResolved will be executed when the any promise is resolved.
    //This callback method should be set by instance creator.
    //It can be set using options parameter in constructor.
    const oThis = this;

    logger.log(oThis.name, " :: a promise has been resolved. resolvedValue:", resolvedValue);
  }

  , onPromiseRejected: function ( rejectReason, promiseContext ) {
    //onPromiseRejected will be executed when the any promise is timedout.
    //This callback method should be set by instance creator.
    //It can be set using options parameter in constructor.
    const oThis = this;

    logger.log(oThis.name, " :: a promise has been rejected. rejectReason: ", rejectReason);
  }

  , onPromiseTimedout: function ( promiseContext ) {
    //onPromiseTimedout will be executed when the any promise is timedout.
    //This callback method should be set by instance creator.
    //It can be set using options parameter in constructor.
    const oThis = this;

    logger.log(oThis.name, ":: a promise has timed out.", promiseContext.executorParams);
  }

  , onMaxZombieCountReached: function () {
    //onMaxZombieCountReached will be executed when maxZombieCount >= 0 && current zombie count (oThis.zombieCount) >= maxZombieCount.
    //This callback method should be set by instance creator.
    //It can be set using options parameter in constructor.
    const oThis = this;

    logger.log(oThis.name, ":: maxZombieCount reached.");

  }

  , onPromiseCompleted: function ( promiseContext ) {
    //onPromiseCompleted will be executed when the any promise is removed from pendingPromise queue.
    //This callback method should be set by instance creator.
    //It can be set using options parameter in constructor.
    const oThis = this;

    logger.log(oThis.name, ":: a promise has been completed.");
  }  
  , onAllPromisesCompleted: function () {
    //onAllPromisesCompleted will be executed when the last promise in pendingPromise is resolved/rejected.
    //This callback method should be set by instance creator.
    //It can be set using options parameter in constructor.
    //Ideally, you should set this inside SIGINT/SIGTERM handlers.

    logger.log("Examples.allResolve :: onAllPromisesCompleted triggered");
    manager.logInfo();
  }
};


const promiseExecutor = function ( resolve, reject, params, promiseContext ) {
  //promiseExecutor
  setTimeout(function () {
    resolve( params.cnt ); // Try different things here.
  }, 1000);
};

const manager = new Base.CustomPromise.QueueManager( promiseExecutor, queueManagerOptions);

// createPromise calls the promiseExecutor
for( let cnt = 0; cnt < 5; cnt++ ) {
  manager.createPromise( {"cnt": (cnt + 1) } );
}

Running test cases

./node_modules/.bin/mocha --recursive "./tests/**/*.js"
You might also like...

A simple library to draw option menu or other popup inputs and layout on Node.js console.

A simple library to draw option menu or other popup inputs and layout on Node.js console.

console-gui-tools A simple library to draw option menu or other popup inputs and layout on Node.js console. console-gui-tools A simple Node.js library

Dec 24, 2022

A plugin that provides utilities for extended backgrounds and borders.

tailwindcss-full-bleed A plugin that provides utilities for extended backgrounds and borders. Demo Installation Install the plugin from npm: npm insta

Dec 24, 2022

Manually curated collection of resources, plugins, utilities, and other assortments for the Sapphire Community projects.

Awesome Sapphire Manually curated collection of resources, plugins, utilities, and other assortments for the Sapphire Community projects. Has your pro

Dec 17, 2022

A plugin that provides utilities for animation property.

tailwindcss-animation-property A plugin that provides utilities for animation property. Not only does the plugin provide the usual animation propertie

Sep 23, 2022

Context-carrying logger with conditional methods.

logger Provides a simple logging interface as well as a LogContext class which carries a context around. Installation npm install @rocicorp/logger Us

May 20, 2022

The JSON logger you always wanted for Lambda.

MikroLog The JSON logger you always wanted for Lambda. MikroLog is like serverless: There is still a logger ("server"), but you get to think a lot les

Nov 15, 2022

A devtool improve your pakage manager use experience no more care about what package manager is this repo use; one line, try all.

pi A devtool improve your pakage manager use experience no more care about what package manager is this repo use; one line, try all. Stargazers over t

Nov 1, 2022

Meogic-tab-manager is an extensible, headless JavaScript tab manager framework.

Meogic-tab-manager is an extensible, headless JavaScript tab manager framework.

MeogicTabManager English document MeogicTabManager是一个有可拓展性的、headless的JavaScript标签页管理框架。 MeogicTabManager旨在提供可自由组装页面框架、自定义页面组件、甚至覆盖框架自带事件响应的开发体验。 Meogi

Oct 8, 2022

A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

A fast and powerful http toolkit that take a list of domains to find active domains and other information such as status-code, title, response-time , server, content-type and many other

HTTPFY curently in beta so you may see problems. Please open a Issue on GitHub and report them! A Incredible fast and Powerful HTTP toolkit Report Bug

Dec 22, 2022
Releases(v1.0)
  • v1.0(May 24, 2022)

    • Base repository is created and all the common functionality which different modules need are moved to it. Example - Logger, response helper, promise context, promise queue manager.
    • Log level support is introduced and non-important logs are moved to debug log level.
    Source code(tar.gz)
    Source code(zip)
Owner
PLG Works
We design, build and deliver highly scalable and secure web and mobile applications using React, Next.js, React Native, Web3.js, Node.js, Ruby On Rails.
PLG Works
Another logger in JS. This one offers a console.log-like API and formatting, colored lines and timestamps (or not if desired), all that with 0 dependencies.

hellog Your new logger ! hellog is a general-purpose logging library. It offers a console.log-like API and formatting, extensible type-safety colored

Maxence Lecanu 4 Jan 5, 2022
A NodeJS Console Logger with superpowers

LogFlake LogFlake is a NodeJS console logger with superpowers. It has the same API as the usual Console but with beautified output, a message header w

Felippe Regazio 57 Oct 9, 2022
An elegant console logger.

kons An elegant console logger. Features Tiny (Minified + Gzipped ≈ 0.1kB). Beautiful. Easy to use. Customizable. TypeScript type declarations include

ʀᴀʏ 6 Aug 13, 2022
Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.

Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.

Lily Scott 3 Feb 28, 2022
Adds promise support (rejects(), doesNotReject()) to tape by decorating it using tape-promise.

Tape With Promises Adds promise support (rejects(), doesNotReject()) to tape by decorating it using tape-promise. Install npm install --save-dev @smal

Small Technology Foundation 3 Mar 21, 2022
logseq custom.js and custom.css utilities : resize query table columns, hide namespaces...

logseq-custom-files custom.js and custom.css utilities for Logseq. current version v20220331 query table view : add handles on the query table headers

null 44 Dec 7, 2022
Deta Base UI - A place with more functionality for managing your Deta Base(s).

Deta Base UI - A place with more functionality for managing your Deta Base(s). ✨ Features: Total rows count Quick multi select (click and shift) Searc

Harman Sandhu 13 Dec 29, 2022
Kuldeep 2 Jun 21, 2022
Colorconsole provides an interesting way to display colored info, success, warning and error messages on the developer console in your browser

ColorConsole NPM Package Colorconsole provides an interesting way to display colored info, success, warning and error messages on the developer consol

Hasin Hayder 17 Sep 19, 2022