The power of Async Hooks in Node.js
Request context example
asyncHooks.createHook({ init, destroy }).enable();
const reqContextMap = new Map();
function createRequestContext (data) {
reqContextMap.set(asyncHooks.executionAsyncId(), data)
}
function getRequestContext () {
return reqContextMap.get(asyncHooks.executionAsyncId())
}
function init (asyncId, type, triggerAsyncId, resource) {
// Store same context data for child async resources
if (reqContextMap.has(triggerAsyncId)) {
reqContextMap.set(asyncId, reqContextMap.get(triggerAsyncId))
}
}
function destroy (asyncId) {
if (reqContextMap.has(asyncId)) {
reqContextMap.delete(asyncId)
}
}
module.exports = {
createRequestContext,
getRequestContext
};
const express = require('express');
const ah = require('./hooks');
const app = express();
const port = 3000;
app.use((request, response, next) => {
const data = { headers: request.headers };
ah.createRequestContext(data);
next();
});
const requestHandler = (request, response, next) => {
const reqContext = ah.getRequestContext();
response.json(reqContext);
next()
};
app.get('/', requestHandler)
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
console.log(`server is listening on ${port}`);
});