HTTP Request Context
Set and get request-scoped context anywhere.
Requirement
Nodejs version >= 8.2.0
This module uses the newer async_hooks API which is considered Experimental
by Nodejs.
Parameter
Parameter configuration must be require before, but normally no config are required.
Name | Description | Default |
---|
process.env.HTTP_REQUEST_CONTEXT_INTERVAL | remove expired callstack interval(ms) | 10000 |
process.env.HTTP_REQUEST_CONTEXT_EXPIRE | callstack expire time(ms) | 150000 |
Middleware
httpRequestContext.middleware
Express middleware.httpRequestContext.koaMiddleware
Koa middleware.
Set Context
httpRequestContext.set(key, value)
Set context anywhere.httpRequestContext.set({ key: value })
This is also OK.
Get Context
httpRequestContext.get(key)
Get the [key]
attribute of the context.httpRequestContext.get()
Gets an object containing all context properties.
How to Use
see example here.
Install
npm install http-request-context --save
Express
Init
const httpRequestContext = require('http-request-context')
app.use(httpRequestContext.middleware)
Set Context
const httpRequestContext = require('http-request-context')
app.use((req, res, next) => {
setTimeout(() => {
httpRequestContext.set('foo', 'bar')
next()
}, 100)
})
Get Context
const httpRequestContext = require('http-request-context')
httpRequestContext.get('foo')
Koa
Init
const httpRequestContext = require('http-request-context')
app.use(httpRequestContext.koaMiddleware)
Set Context
const httpRequestContext = require('http-request-context')
app.use(async (ctx, next) => {
await new Promise(resolve => {
setTimeout(() => {
httpRequestContext.set('user', 'user')
resolve()
}, 300)
})
await next()
})
Get Context
const httpRequestContext = require('http-request-context')
httpRequestContext.get('foo')
Tips
MySQL
If you init mysql connect before http server start, you may get context undefined in mysql query callback scope.
googleapis/cloud-trace-nodejs #946
nodejs/node #22360
mysqlConnection.query('SELECT * FROM table', (error, results, fields) => {
httpRequestContext.get('foo')
})
You can use util.promisify to avoid it.
util.promisify(mysqlConnection.query).bind(mysqlConnection)('SELECT * FROM table')
.then((results, fields) => {
httpRequestContext.get('foo')
})
.catch(error => {})