Coder Social home page Coder Social logo

ostdotcom / base Goto Github PK

View Code? Open in Web Editor NEW
18.0 17.0 1.0 439 KB

OST Base provides advanced Promise Queue Manager and other utilities.

Home Page: https://ost.com

License: GNU Lesser General Public License v3.0

JavaScript 100.00%
ost logger response-formatter openst promise-queue

base's Introduction

OST Base provides advanced Promise Queue Manager and other utilities.

Build Status npm version

Install

npm install @ostdotcom/base --save

PromiseQueueManager Usage

const OSTBase = require('@ostdotcom/base'),
  logger  = new OSTBase.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 OSTBase.OSTPromise.QueueManager( promiseExecutor, queueManagerOptions);

for( let cnt = 0; cnt < 50; cnt++ ) {
  manager.createPromise( {"cnt": (cnt + 1) } );
}

Logger Usage

const OSTBase = require('@ostdotcom/base'),
  Logger  = OSTBase.Logger,
  logger  = new Logger("my_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 irrespcetive 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 usage

const rootPrefix = '.',
  paramErrorConfig = require(rootPrefix + '/tests/mocha/lib/formatter/param_error_config'),
  apiErrorConfig = require(rootPrefix + '/tests/mocha/lib/formatter/api_error_config');

const OSTBase = require('@ostdotcom/base'),
  ResponseHelper  = OSTBase.responseHelper,
  responseHelper = new ResponseHelper({
      moduleName: 'companyRestFulApi'
  });
    
//using error function
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   
  }
});
    
//using paramValidationError function
responseHelper.paramValidationError({
  internal_error_identifier:"s_vt_2", 
  api_error_identifier: "test_1", 
  params_error_identifiers: ["user_name_inappropriate"], 
  debug_options: {id: 1234},
  error_config: {
    param_error_config: paramErrorConfig,
    api_error_config: apiErrorConfig   
  }
});

// Result object is returned from responseHelper method invocations above, we can chain several methods as shown below
    
responseHelper.error({
  internal_error_identifier: 's_vt_1', 
  api_error_identifier: 'invalid_api_params',
  debug_options: {id: 1234},
  error_config: {
    param_error_config: paramErrorConfig,
    api_error_config: apiErrorConfig   
  }
}).isSuccess();

responseHelper.error({
  internal_error_identifier: 's_vt_1', 
  api_error_identifier: 'invalid_api_params',
  debug_options: {id: 1234},
  error_config: {
    param_error_config: paramErrorConfig,
    api_error_config: apiErrorConfig   
  }
}).isFailure();

responseHelper.error({
  internal_error_identifier: 's_vt_1', 
  api_error_identifier: 'invalid_api_params',
  debug_options: {id: 1234},
  error_config: {
    param_error_config: paramErrorConfig,
    api_error_config: apiErrorConfig   
  }
}).toHash();    

base's People

Contributors

alpeshvmodi avatar anaghamurtarkar avatar ashutoshlodhi avatar bala007 avatar bitsnacker avatar kedarchandrayan avatar mayurpatil888 avatar puneet-khushwani-eth avatar sachin-chauhan-dev avatar sunilkhedar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

hitesh23k

base's Issues

Do JS styling changes in openst-platform of follow the common style guide followed across all openst repos.

PROBLEM : Making sure a coding style is properly followed is a big undertaking, it often slips through the cracks leaving the work inconsistent across repos.

SOLUTION
We came across Prettier https://prettier.io/ that automatically style the code. This will help the codebase be uniform and easier to read alongwith saving good amount of our time.

Prettier supports:

JavaScript, including ES2017
JSX
Flow
TypeScript
CSS, Less, and SCSS
JSON
GraphQL
Markdown, including GFM
YAML
It removes all original styling and ensures the outputted code conforms to a consistent style. (See this post)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.