|
1 | 1 | # node-execution-context |
2 | | -Nodejs execution context. |
| 2 | +A straightforward library that provides a persistent process-level context wrapper using node "async_hooks" feature. |
| 3 | + |
| 4 | +## Installation |
| 5 | + |
| 6 | +``` |
| 7 | +npm i node-execution-context |
| 8 | +``` |
| 9 | + |
| 10 | +## Getting started |
| 11 | + |
| 12 | +Let't start with creating the context initialisation point of our app, well take an simples express app for this example |
| 13 | + |
| 14 | +```js |
| 15 | +// main.js |
| 16 | + |
| 17 | +const Context = require('node-execution-context'); |
| 18 | +const express = require('express'); |
| 19 | +const UserController = require('./controllers/user'); |
| 20 | +const app = express(); |
| 21 | +const port = 3000; |
| 22 | + |
| 23 | +const ContextMiddleware = (req, res, next) => { |
| 24 | + Context.create({ |
| 25 | + reference: req.body.reference |
| 26 | + }); |
| 27 | + |
| 28 | + next(); |
| 29 | +}; |
| 30 | + |
| 31 | +app.use('/', ContextMiddleware); |
| 32 | +app.post('/user', UserController.create); |
| 33 | + |
| 34 | +app.listen(port); |
| 35 | + |
| 36 | +``` |
| 37 | + |
| 38 | +This will expose the request-level context to all future points that will handle this request making it exposable by accessing the context |
| 39 | + |
| 40 | +```js |
| 41 | +// ./controller/user/index.js |
| 42 | + |
| 43 | +const Context = require('node-execution-context'); |
| 44 | +const mongo = require('../service/mongo'); |
| 45 | +const logger = require('../service/logger'); |
| 46 | + |
| 47 | +export class UserController { |
| 48 | + async create (req, res, next) { |
| 49 | + const { user } = req.body; |
| 50 | + const { reference } = Context.get(); |
| 51 | + |
| 52 | + logger.info('Created user for reference: ', reference); |
| 53 | + |
| 54 | + return await mongo.create('user', user); |
| 55 | + } |
| 56 | +} |
| 57 | +``` |
0 commit comments