0.0.2 • Published 8 months ago

@redhare/context v0.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

@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 requestoptions.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
0.0.2

8 months ago

0.0.1

8 months ago