@redhare/context
v0.0.2
Published
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.
Downloads
2
Keywords
Readme
@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 isx-request-id
, it define the key name of the response header which contain requestId.options.upstreamRequestIdKey
default value isx-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 newUUID
. This id will also add into http response headers, header key name is decide byoptions.requestIdKey
infraRequestContext.userInfo
reserved for google login save userInfoinfraRequestContext.userInfoEncrypt
reserved for google login save userInfoinfraRequestContext.extra
reserved for user can save anything you need