Persistent execution context allowing you to get/set the context anywhere implemented using async hooks. Can be used to create request level execution context, a stack trace that persists through async resources, or anything else you need to survive the e
npm install @mondaydotcomorg/node-execution-context
$ npm install @mondaydotcomorg/node-execution-context
`or with yarn:
`
$ yarn add @mondaydotcomorg/node-execution-context
`Getting Started
Let's create a service that will use our library in order to create and get context.
`javascript
const contextProvider = require('@mondaydotcomorg/node-execution-context');function createExecutionContext(contextData) {
contextProvider.createExecutionContext(contextData);
};
function getExecutionContext() {
const context = contextProvider.getExecutionContext();
return context;
};
module.exports = {
getExecutionContext,
createExecutionContext
};
`Now wherever we want in our code we can pass an object to createExecutionContext and it will be saved and accesible for any async resources descendant from that place forward.
For example let's do this in a middleware that is the first thing that runs on a new request.
`javascript
const executionContextService = require('services/execution-context-service');async function authenticationMiddleware(req, res, next) {
const { accountPermissions } = req.body
executionContextService.createExecutionContext({
accountPermissions,
method: req.method,
});
next();
}
`Now we can use this context later and be certain that the request being handled is the same one for which we are getting our context.
`javascript
const executionContextService = require('services/execution-context-service');
const eventModelService = require('services/event-model-service');async function createNewEvent(eventData) {
const { accountPermissions } = executionContextService.getExecutionContext();
eventModelService.createEvent(accountPermissions, eventData);
}
``Optional Params: traceOptions can be passed if you want to set some initial trace data into the trace and have the context add a trace detailing async Id and resource type each time context is updated. If you do not pass this object the trace is never created. This can be used for debugging or for enriching logs, however should not be passed if not needed as this will be added fro every async resource created.