पाठ 9 / 30

Route Handlers और स्टेटस कोड

प्रभावी handlers लिखें और HTTP response codes को नियंत्रित करें।

Async handlers डेटा return करते हैं

Fastify handlers async functions हैं। Object return करें और Fastify इसे auto-serialize करके JSON भेज देता है और 200 OK भेजता है।

Custom स्टेटस कोड

भेजने से पहले custom HTTP status सेट करने के लिए reply.code() या reply.status() उपयोग करें।

fastify.post('/items', async (req, reply) => {
  const item = { id: 1, name: 'Widget' };
  return reply.code(201).send(item);
});

fastify.get('/missing', async (req, reply) => {
  return reply.code(404).send({ error: 'Not found' });
});

fastify.delete('/items/:id', async (req, reply) => {
  return reply.code(204).send();
});

Handler options (schema, auth, आदि)

Fastify routes एक optional third argument स्वीकार करते हैं metadata के साथ—validation के लिए schema, permission checks के लिए auth।