Fastify And Ajv Schema Validation
Solution 1:
this schema structure solved my problem. Just in case if someone wants to check it out if they run into similar issue.
constquerySchema= {
schema: {
querystring: {
type:'object',
properties: {
hccid: {
type:'string'
}
},
required: ['hccid']
}
}
}
Solution 2:
According to the docs, you can use the querystring
or query
to validate the query string and params
to validate the route params.
Params would be:
/api/garage/:id
whereid
is the param accessiblerequest.params.id
/api/garage/:plate
whereplate
is the param accessible atrequest.params.plate
Example for param validation would be:
constgetItems = (req, reply) => {
const { plate } = req.params;
delete req.params.plate;
reply.send(plate);
};
const getItemsOpts = {
schema: {
description: "Get information about a particular vehicle present in garage.",
params: {
type: "object",
properties: {
plate: {
type: "string",
pattern: "^[A-Za-z0-9]{7}$",
},
},
},
response: {
200: {
type: "array",
},
},
},
handler: getItems,
};
fastify.get("/garage/:plate", getItemsOpts);
done();
Query / Querystring would be:
/api/garage/id?color=white&size=small
wherecolor
andsize
are the two querystrings accessible atrequest.query.color
orrequest.query.size
.
Please refer to the above answer as an example fro query validation.
Validation
The route validation internally relies upon Ajv v6 which is a high-performance JSON Schema validator. Validating the input is very easy: just add the fields that you need inside the route schema, and you are done!
The supported validations are:
body
: validates the body of the request if it is a POST, PUT, or PATCH method.querystring
orquery
: validates the query string.params
: validates the route params.headers
: validates the request headers.
[1] Fastify Validation: https://www.fastify.io/docs/latest/Validation-and-Serialization/#validation
[2] Ajv@v6: https://www.npmjs.com/package/ajv/v/6.12.6
[3] Fastify Request: https://www.fastify.io/docs/latest/Request/
Post a Comment for "Fastify And Ajv Schema Validation"