पाठ 14 / 32
Middleware और Hooks Pattern
Classic middleware chains की जगह Fastify hooks से logging, authentication और rate limiting लागू करें।
Middleware के बजाय hooks क्यों?
Fastify के hooks traditional middleware chains से अधिक explicit और performant हैं। हर hook के पास request lifecycle में एक स्पष्ट भूमिका है।
Hooks के साथ Logging middleware
आने वाले को log करने के लिए onRequest, outgoing को log करने के लिए onSend उपयोग करें।
fastify.addHook('onRequest', async (request, reply) => {
request.startTime = Date.now();
});
fastify.addHook('onSend', async (request, reply, payload) => {
const duration = Date.now() - request.startTime;
fastify.log.info({
method: request.method,
url: request.url,
statusCode: reply.statusCode,
duration,
});
return payload;
});