Initial curated projectbrain source from 8a7b1e0651dbdab97d744cbd2e653ab3970ac6c5
This commit is contained in:
commit
5aa3e8d685
700 files changed
+132801
No files matched your search
@@ -0,0 +1,32 @@
|
||||
import type { FastifyInstance, FastifyRequest } from "fastify";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
declare module "fastify" {
|
||||
interface FastifyRequest {
|
||||
requestId: string;
|
||||
}
|
||||
}
|
||||
|
||||
const firstHeaderValue = (
|
||||
value: string | string[] | undefined,
|
||||
): string | undefined => (Array.isArray(value) ? value[0] : value);
|
||||
|
||||
export const createRequestId = (
|
||||
incomingRequestId: string | string[] | undefined,
|
||||
): string => {
|
||||
const requestId = firstHeaderValue(incomingRequestId);
|
||||
|
||||
return requestId && /^[A-Za-z0-9_-]{1,128}$/.test(requestId)
|
||||
? requestId
|
||||
: `req-${randomUUID()}`;
|
||||
};
|
||||
|
||||
export const requestIdPlugin = async (app: FastifyInstance) => {
|
||||
app.addHook("onRequest", async (request, reply) => {
|
||||
request.requestId = request.id;
|
||||
reply.header("x-request-id", request.requestId);
|
||||
});
|
||||
};
|
||||
|
||||
export const getRequestId = (request: FastifyRequest): string =>
|
||||
request.requestId ?? request.id ?? `req-${randomUUID()}`;
|
||||
Reference in new issue
Block a user