20 lines
656 B
TypeScript
20 lines
656 B
TypeScript
import { Injectable, NestMiddleware } from '@nestjs/common';
|
|
import { Request, Response, NextFunction } from 'express';
|
|
import { randomUUID } from 'crypto';
|
|
import { RequestContextService } from './request-context.service';
|
|
|
|
@Injectable()
|
|
export class RequestContextMiddleware implements NestMiddleware {
|
|
constructor(private readonly ctx: RequestContextService) {}
|
|
|
|
use(req: Request, _: Response, next: NextFunction) {
|
|
const context = {
|
|
requestId: randomUUID(),
|
|
correlationId: (req.headers['x-correlation-id'] as string) ?? undefined,
|
|
headers: req.headers as Record<string, string>,
|
|
};
|
|
|
|
this.ctx.run(context, next);
|
|
}
|
|
}
|