b6ba4c61f7
* feat(server): req context for subscription connections too * minor adjustment
41 lines
983 B
TypeScript
41 lines
983 B
TypeScript
import { REQUEST_ID_HEADER } from '@/logging/expressLogging'
|
|
import { asyncRequestContextEnabled } from '@/modules/shared/helpers/envHelper'
|
|
import type express from 'express'
|
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
|
|
type StorageType = {
|
|
requestId: string
|
|
dbMetrics: {
|
|
totalDuration: number
|
|
totalCount: number
|
|
}
|
|
}
|
|
|
|
const storage = asyncRequestContextEnabled()
|
|
? new AsyncLocalStorage<StorageType>()
|
|
: undefined
|
|
|
|
export const initiateRequestContextMiddleware: express.RequestHandler = (
|
|
req,
|
|
_res,
|
|
next
|
|
) => {
|
|
const reqId = req.headers[REQUEST_ID_HEADER] || 'unknown'
|
|
enterNewRequestContext({ reqId: reqId as string })
|
|
next()
|
|
}
|
|
|
|
export const enterNewRequestContext = (params: { reqId: string }) => {
|
|
const { reqId } = params
|
|
const store: StorageType = {
|
|
requestId: reqId,
|
|
dbMetrics: {
|
|
totalCount: 0,
|
|
totalDuration: 0
|
|
}
|
|
}
|
|
storage?.enterWith(store)
|
|
}
|
|
|
|
export const getRequestContext = () => storage?.getStore()
|