Socket
Socket
Sign inDemoInstall

node-execution-context

Package Overview
Dependencies
63
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    node-execution-context

Provides execution context wrapper for node JS, can be used to create execution wrapper for handling requests and more


Version published
Maintainers
1
Created

Readme

Source

node-execution-context

A straightforward library that provides a persistent process-level context wrapper using node "async_hooks" feature.

Installation

npm i node-execution-context

Getting started

Let't start with creating the context initialisation point of our app, well take an simples express app for this example

// main.js

const express = require('express');
const { AsyncResource } = require('async_hooks');
const Context = require('node-execution-context');
const UserController = require('./controllers/user');
const app = express();
const port = 3000;

const ContextMiddleware = (req, res, next) => {
    Context.run(next, { val: true });
};

app.use('/', ContextMiddleware);
app.post('/user', UserController.create);

app.listen(port);

This will expose any point of your code form this point that handles that request.

// ./controller/user/index.js

const Context = require('node-execution-context');
const mongo = require('../service/mongo');
const logger = require('../service/logger');

export class UserController {
    async create (req) {
        const { user } = req.body;
        
        // This will return the reference number set by out ContextMiddleware
        const { reference } = Context.get();
        
        logger.info('Created user for reference: ', reference);
        
        return await mongo.create('user', user);
    }
}

API

create(initialContext?: object)

Creates for the current async resource an execution context entry identified with his asyncId. Any future processes that will be added to the async execution chain will be exposed to this context.

update(update: object)

Updates the current execution context with a given update obect.

get()

Returns the current execution context identified with the current asyncId.

run(fn: Function, initialContext: object)

Runs a given function under a dedicated AsyncResource, exposing given initial context to the process and it's child processes.

monitor(): ExecutionMapUsage

Returns an monitoring report over the current execution map resources

API Usage

const Context = require('node-execution-context');

Context.create({
    value: true
});

Promise.resolve().then(() => {
    console.log(Context.get()); // outputs: {"value": true}
    
    Context.update({
        value: false
    });
    
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(Context.get()); // outputs: {"value": false}
            
            Context.update({
                butter: 'fly'
            });
            
            process.nextTick(() => {
                console.log(Context.get()); // outputs: {"value": false, "butter": 'fly'}
                resolve();
            });
            
        }, 1000);
        
        console.log(Context.get()); // outputs: {"value": true}
        console.log(Context.monitor) // Will result with monitor result 
    });
});

The following errors can be thrown while accessing to the context API :

Codewhen
CONTEXT_ALREADY_DECLAREDWhen trying to create execution context, but current async resource already exists.
CONTEXT_DOES_NOT_EXISTSWhen try to get / update the context, but it yet been created.

Keywords

FAQs

Last updated on 24 Aug 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc