Import source: app/backend/src/plugins/request-id
Import the existing local project snapshot. This commit organizes existing files; it does not represent newly developed functionality.
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import fp from 'fastify-plugin';
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
const HEADER = 'x-request-id';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
requestId: string;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(async function requestIdPlugin(app: FastifyInstance) {
|
||||
app.addHook('onRequest', async (req: FastifyRequest, _reply: FastifyReply) => {
|
||||
const incoming = req.headers[HEADER];
|
||||
req.requestId = typeof incoming === 'string' && incoming.length > 0
|
||||
? incoming.slice(0, 64)
|
||||
: randomBytes(12).toString('hex');
|
||||
});
|
||||
|
||||
app.addHook('onSend', async (_req: FastifyRequest, reply: FastifyReply) => {
|
||||
reply.header(HEADER, _req.requestId);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user