पाठ 10 / 32
JSON Schema और वैलिडेशन
JSON Schema से request bodies, queries और params validate करें, और अमान्य input अपने-आप reject करें।
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 [];
});schema से body validate करना
Fastify schema को startup पर Ajv से compile करता है।
requiredmissing fields reject करता है।- गलत input पर handler चलने से पहले
400मिलता है।
const fastify = require('fastify')();
fastify.post('/user', {
schema: {
body: {
type: 'object',
required: ['name'],
properties: { name: { type: 'string', minLength: 2 } }
}
}
}, async (req) => ({ hello: req.body.name }));
fastify.listen({ port: 3000 });त्वरित जाँच
त्वरित जाँच: response schema Fastify को तेज़ क्यों बनाता है?
- यह database cache करता है
- यह generic JSON.stringify की जगह specialised serializer compile करता है
- यह logging बंद करता है
Answer
यह generic JSON.stringify की जगह specialised serializer compile करता है — fast-json-stringify schema से serialization code बनाता है, और undeclared fields हटा भी देता है।