forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcorrelation-id.middleware.ts
More file actions
41 lines (35 loc) · 1.21 KB
/
Copy pathcorrelation-id.middleware.ts
File metadata and controls
41 lines (35 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Injectable, NestMiddleware } from "@nestjs/common";
import { randomUUID } from "node:crypto";
import { NextFunction, Request, Response } from "express";
import { RequestContextService } from "./request-context.service";
const CORRELATION_HEADER = "x-correlation-id";
const REQUEST_ID_HEADER = "x-request-id";
@Injectable()
export class CorrelationIdMiddleware implements NestMiddleware {
constructor(private readonly requestContext: RequestContextService) {}
use(req: Request, res: Response, next: NextFunction): void {
const incoming =
this.readHeader(req, CORRELATION_HEADER) ??
this.readHeader(req, REQUEST_ID_HEADER);
const correlationId = incoming ?? randomUUID();
res.setHeader(CORRELATION_HEADER, correlationId);
void this.requestContext.runWithContext(
{
correlationId,
traceId: correlationId,
httpMethod: req.method,
httpPath: req.originalUrl ?? req.url,
},
() => {
next();
},
);
}
private readHeader(req: Request, name: string): string | undefined {
const value = req.headers[name];
if (typeof value === "string" && value.trim().length > 0) {
return value.trim();
}
return undefined;
}
}