@redhare/context v0.0.2
@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.requestIdKeydefault value isx-request-id, it define the key name of the response header which contain requestId.options.upstreamRequestIdKeydefault 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.requestIdis a uuid for every request which first get from requestoptions.requestIdKey, if not exist, will generate a newUUID. This id will also add into http response headers, header key name is decide byoptions.requestIdKeyinfraRequestContext.userInforeserved for google login save userInfoinfraRequestContext.userInfoEncryptreserved for google login save userInfoinfraRequestContext.extrareserved for user can save anything you need