@redhare/context
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

@infra-node-kit/context

In NestJS we need a context which can be created for every request. This context can contains some information we need for any place can be access.

Since AsyncLocalStorage is used internally, the required Node.js version is >=14.15.2 that includes significant fixes.

Installation

yarn add '@infra-node-kit/context'

Basic Usage

first you need use the infraContextMiddleware first, in middleware will create context and add requestId on context.

import { infraContextMiddleware } from '@infra-node-kit/context';

const app = await NestFactory(AppModule);
...
app.use(infraContextMiddleware());

await app.listen(3000);

In you controller, service or any other place can import InfraRequestContext to get the context.

import { InfraRequestContext } from '@infra-node-kit/context'
@Controller('')
export class MyController {
  @Get()
  test(): string {
    const ctx: InfraRequestContext = InfraRequestContext.get()
    return ctx.requestId
  }
}

API

infraContextMiddleware(options)

  • options.requestIdKey default value is x-request-id, it define the key name of the response header which contain requestId.
  • options.upstreamRequestIdKey default value is x-request-id, it define the key name of the request header which contain requestId, if request has this header, the project will reuse this value.

InfraRequestContext.get()

  • this method can get the context object which the type is InfraRequestContext

infraRequestContext

infraRequestContext = InfraRequestContext.get()

  • infraRequestContext.requestId is a uuid for every request which first get from request[options.requestIdKey], if not exist, will generate a new UUID. This id will also add into http response headers, header key name is decide by options.requestIdKey

  • infraRequestContext.userInfo reserved for google login save userInfo

  • infraRequestContext.userInfoEncrypt reserved for google login save userInfo

  • infraRequestContext.extra reserved for user can save anything you need

Readme

Keywords

none

Package Sidebar

Install

npm i @redhare/context

Weekly Downloads

2

Version

0.0.2

License

ISC

Unpacked Size

99.7 kB

Total Files

14

Last publish

Collaborators

  • tobywan
  • yann001
  • jiushu
  • keyunlei
  • zsynuting