पाठ 10 / 30

JSON Schema और वैलिडेशन

JSON Schema के साथ strict data contracts परिभाषित करें और लागू करें।

Schema-driven validation

Fastify JSON Schema का उपयोग request bodies, query strings, और URL parameters को validate करने के लिए करता है। Invalid requests को automatically 400 Bad Request से reject किया जाता है।

Schema परिभाषित करना

Route options में एक schema object pass करें। यह body, querystring, params, और response को validate कर सकता है।

const createItemSchema = {
  body: {
    type: 'object',
    required: ['name', 'price'],
    properties: {
      name: { type: 'string' },
      price: { type: 'number', minimum: 0 },
    },
  },
};

fastify.post('/items', { schema: createItemSchema }, async (req) => {
  // req.body is guaranteed to have name and price
  return { id: 1, ...req.body };
});

Query और params schemas

URL parameters और query strings को उसी तरह validate करें।

const listSchema = {
  querystring: {
    type: 'object',
    properties: {
      page: { type: 'integer', minimum: 1 },
      limit: { type: 'integer', minimum: 1, maximum: 100 },
    },
  },
  params: {
    type: 'object',
    required: ['userId'],
    properties: {
      userId: { type: 'string' },
    },
  },
};

fastify.get('/users/:userId/items', { schema: listSchema }, async (req) => {
  return [];
});