npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

http-request-context

v0.3.1

Published

Store context in http middleware lifecycle.

Downloads

239

Readme

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

Do not use any middleware that contains asynchronous operations before this middleware.

  • 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 terminal 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 => {})