Coder Social home page Coder Social logo

http-request-context's Introduction

HTTP Request Context

npm package

Build Status Coverage Status Known Vulnerabilities FOSSA Status npm package

NPM downloads Dependency Status Dependency Status Standard - JavaScript Style Guide

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.

Options

Option Description Type Default
interval remove expired callstack interval(s) Number 10
expire callstack expire time(s) Number 150
removeAfterFinish remove callstack after http.ServerResponse finish Boolean false
removeAfterClose remove callstack after http.ServerResponse close Boolean false

options.interval

Remove expired callstack interval, used like setInterval(removeExpiredCallstack, interval).

options.expire

Callstack expire time, must be longer than full lifecycle of a request.

options.removeAfterFinish

It will actively remove the relevant callstack after http.ServerResponse finish.

If set to true, you can get the context synchronously in the finish event, but not asynchronous. The benefit is that it can improve the performance of this middleware.

options.removeAfterClose

This is very similar to options.removeAfterFinish, the difference is that after the close event.

Please Note! if set to true, in some cases, the close event may be caused by the client terminating the request, after the close event, we may still use the context after the incomplete asynchronous operation is completed, this will result in loss of context.

Init Middleware

This module is recommend as a "top-level" middleware for ensure all context can be tracked

  • httpRequestContext.middleware(options) Init Express middleware.
  • httpRequestContext.koaMiddleware(options) Init 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

import httpRequestContext from 'http-request-context'

app.use(httpRequestContext.middleware())

Set Context

import httpRequestContext from 'http-request-context'

// set context by key-value
app.use((req, res, next) => {
  setTimeout(() => {
    httpRequestContext.set('foo', 'bar')
    next()
  }, 100)
})

Get Context

import httpRequestContext from 'http-request-context'

httpRequestContext.get('foo') // 'bar'

Koa

Init

import httpRequestContext from 'http-request-context'

app.use(httpRequestContext.koaMiddleware())

Set Context

import httpRequestContext from 'http-request-context'

// set context by key-value
app.use(async (ctx, next) => {
  await new Promise(resolve => {
    setTimeout(() => {
      httpRequestContext.set('user', 'user')
      resolve()
    }, 300)
  })
  await next()
})
Get Context
import httpRequestContext from 'http-request-context'

httpRequestContext.get('foo') // 'bar'

Lost Context Tips

http.ServerResponse close event

Sometimes, when client terminate request by close window or reload page, it will cause http.ServerResponse emit 'close' event, this event is trigger by root, so it break away from current request scope, in this case, we can add res(express) or ctx.res(koa) parameter to get context function to ensure context can be tracked, as follows:

// Express
res.on('close', () => {
  console.log('close', httpRequestContext.get('foo', res))
})

// Koa
ctx.res.on('close', () => {
  console.log('close', httpRequestContext.get('foo', ctx.res))
})

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') // undefined
})

You can use util.promisify to avoid it.

util.promisify(mysqlConnection.query).bind(mysqlConnection)('SELECT * FROM table')
  .then((results, fields) => {
    httpRequestContext.get('foo') // 'bar'
  })
  .catch(error => {})

http-request-context's People

Contributors

zhujun24 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

http-request-context's Issues

passport中间件影响上下文

环境
app: https://github.com/appsecco/dvna
node: v12.16.1

在dvna上,如果http-request-context在passport中间件之前使用上下文将会丢失,从当前executionAsyncId往上查找,找不到rootId
看了cls_hooked 和express-http-context 的issues都存在这个问题,
如果将http-request-context 在passport中间件之后使用,则可以获取上下文

removeAfter* is broken on keep-alive connections

it ends with

TypeError: Cannot set property 'data' of undefined
at middleware (/path/to/node_modules/http-request-context/index.js:89:29)

if either removeAfterFinish or removeAfterClose is set to true. the first request

and I guess if the connection is kept alive longer than options.alive, it will be out of order, either...

acoording to the document and your zhihu zhuanlan,

The TCPWRAP is the new connection from the client. When a new connection is made, the TCPWrap instance is immediately constructed.

i guess that connection and request might not be a 1:1 map.
emmm... but not sure. because i'm using it with koa-convert.back for koav1 compatibility. haven't dig deeply into async_hooks internal yet.

Testing with jest

When I run my tests with jest three of them returns:
Jest has detected the following 3 open handles potentially keeping Jest from exiting

Pointing this part of the code:

       28 |       .use(express.json({ limit: '100mb' }))
       29 |       .use(express.urlencoded({ limit: '100mb', extended: true }))
       30 |       .use(httpContext.middleware({
          |                        ^
      31 |         removeAfterClose: true,
      32 |         removeAfterFinish: true,
      33 |       }))

      at interval (node_modules/http-request-context/index.js:22:3)
      at Object.middleware (node_modules/http-request-context/index.js:119:5)
      at new WebApp (src/infra/web/index.ts:30:24)

Any ideia what am I doing wrong? Already tried to move the middleware to other parts of the express instantiation but the problem remains.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.