Namespaces
Local storage across async operations using the async_hooks
experimental module
Example
import { Namespace } from '@lleon/namespaces'
const ns = new Namespace('my-namespace').enable().createStore();
async function findUser() {
return { name: 'John' };
}
findUser()
.then(user => {
ns.set('user', user);
})
.then(() => {
setTimeout(() => {
console.log(ns.get('user')); // { "name": "John" }
}, 1000);
});
Using Express
import express from 'express';
import { Namespace } from '@lleon/namespaces',
const ns = new Namespace('express-ns').enable();
const app = express();
app.use(ns.express());
app.get('/', (req, res, next) => {
console.log(ns.get('req') === req); // true
console.log(ns.get('res') === res); // true
});
app.listen(3000);
Using Restify
import restify from 'restify';
import { Namespace } from '@lleon/namespaces',
const ns = new Namespace('restify-ns').enable();
const server = restify.createServer();
server.use(ns.restify());
server.get('/', (req, res, next) => {
console.log(ns.get('req') === req); // true
console.log(ns.get('res') === res); // true
})
server.listen(3000);
Using Hapi
import hapi from 'hapi';
import { Namespace } from '@lleon/namespaces',
const ns = new Namespace('hapi-ns').enable();
const server = new hapi.Server();
server.connection({ host: '0.0.0.0', port: 3000 });
server.ext('onRequest', ns.hapi());
server.route({
method: 'get',
url: '/',
handler(request, reply) {
console.log(ns.get('request') === request); // true
console.log(ns.get('reply') === reply); // true
}
});
server.start();