Giter Club home page Giter Club logo

fastify-request-context's Introduction

@fastify/request-context

NPM Version NPM Downloads Build Status Coverage Status

Request-scoped storage support, based on Asynchronous Local Storage (which uses native Node.js ALS with fallback to cls-hooked for older Node.js versions)

Inspired by work done in @fastify/http-context.

This plugin introduces thread-local request-scoped http context, where any variables set within the scope of a single http call won't be overwritten by simultaneous calls to the api nor will variables remain available once a request is completed.

Frequent use-cases are persisting request-aware logger instances and user authorization information.

Getting started

First install the package:

npm i @fastify/request-context

Next, set up the plugin:

const { fastifyRequestContextPlugin } = require('@fastify/request-context')
const fastify = require('fastify');

fastify.register(fastifyRequestContextPlugin, { 
  hook: 'preValidation',
  defaultStoreValues: {
    user: { id: 'system' } 
  }
});

Note that when you mutate the object got from the request context it will affect future requests. To prevent this behaviour you can use defaultStoreValues factory:

const { fastifyRequestContextPlugin } = require('@fastify/request-context')
const fastify = require('fastify');

fastify.register(fastifyRequestContextPlugin, {
  hook: 'preValidation',
  defaultStoreValues: () => ({
    user: { id: 'system' }
  })
});

This plugin accepts options hook and defaultStoreValues.

  • hook allows you to specify to which lifecycle hook should request context initialization be bound. Note that you need to initialize it on the earliest lifecycle stage that you intend to use it in, or earlier. Default value is onRequest.
  • defaultStoreValues sets initial values for the store (that can be later overwritten during request execution if needed). This is an optional parameter.

From there you can set a context in another hook, route, or method that is within scope.

Request context (with methods get and set) is exposed by library itself, but is also available as decorator on fastify.requestContext app instance as well as on req request instance.

For instance:

const { fastifyRequestContextPlugin, requestContext } = require('@fastify/request-context')
const fastify = require('fastify');

const app = fastify({ logger: true })
app.register(fastifyRequestContextPlugin, { 
  defaultStoreValues: {
    user: { id: 'system' } 
  }
});

app.addHook('onRequest', (req, reply, done) => {
  // Overwrite the defaults.
  // This is completely equivalent to using app.requestContext or just requestContext 
  req.requestContext.set('user', { id: 'helloUser' });
  done();
});

// this should now get `helloUser` instead of the default `system`
app.get('/', (req, reply) => {
  // requestContext singleton exposed by the library retains same request-scoped values that were set using `req.requestContext`
  const user = requestContext.get('user');
  reply.code(200).send( { user });
});

app.get('/decorator', function (req, reply) {
  // requestContext singleton exposed as decorator in the fastify instance and can be retrieved:
  const user = this.requestContext.get('user'); // using `this` thanks to the handler function binding
  const theSameUser = app.requestContext.get('user'); // directly using the `app` instance
  reply.code(200).send( { user });
});

app.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  app.log.info(`server listening on ${address}`)
});

return app.ready()

Typescript

In TypeScript you can augment the module to type your context:

import {requestContext} from '@fastify/request-context'

declare module '@fastify/request-context' {
  interface RequestContextData {
    foo: string
  }
}

// Type is string
const foo = requestContext.get('foo')
// Type for unspecified keys is any
const bar = requestContext.get('bar')

If you have "strictNullChecks": true configured for Typescript project, you will notice that the type of the returned value can still be undefined even though the RequestContextData interface has a speicfic type:

// with "strictNullChecks": true

import {requestContext} from '@fastify/request-context'

declare module '@fastify/request-context' {
  interface RequestContextData {
    foo: string
  }
}

// Type is string | undefined
const foo = requestContext.get('foo')

This also occurs if you have "strict": true configured, since enabling Typescript strict mode includes turning on "strictNullChecks". For a discussion about how to work around this and the pros/cons of doing so, please read this issue (#93).

fastify-request-context's People

Contributors

dependabot[bot] avatar kibertoad avatar fdawgs avatar github-actions[bot] avatar jsumners avatar eomm avatar darkgl0w avatar gbalcewicz avatar silenceisgolden avatar awlayton avatar ddadaal avatar mcollina avatar salmanm avatar

Watchers

James Cloos avatar

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.