पाठ 13 / 30

Lifecycle Hooks

Request/response cycle में विशिष्ट बिंदुओं पर code चलाएँ।

Fastify में Hook points

Fastify के पास hooks हैं: onRequest, preValidation, preHandler, onSend, onResponse, और अधिक। उन्हें middleware-like logic चलाने या requests को intercept करने के लिए उपयोग करें।

सामान्य hooks

Globally या per-route hooks रजिस्टर करें। वे sequence में चलते हैं और request/response को modify कर सकते हैं।

// Global hook: log every request
fastify.addHook('onRequest', async (request, reply) => {
  console.log(`${request.method} ${request.url}`);
});

// Global hook: add timing header
fastify.addHook('onSend', async (request, reply, payload) => {
  reply.header('X-Response-Time', `${Date.now() - request.startTime}ms`);
  return payload;
});

// Per-route hook: validate auth token
fastify.get('/admin', 
  { onRequest: async (req, reply) => {
    const token = req.headers.authorization;
    if (!token) return reply.status(401).send({ error: 'Unauthorized' });
  }},
  async () => ({ message: 'Admin access granted' })
);

त्वरित जाँच: कौन-सा hook validation के बाद लेकिन handler से पहले चलता है?

  • onRequest
  • preValidation
  • preHandler
Answer

preHandler — preHandler validation के बाद और route handler से पहले चलता है। इसे auth checks या last-minute data preparation के लिए उपयोग करें।