Skip to content Skip to sidebar Skip to footer

Fastify And Ajv Schema Validation

I am trying to validate the querystring parameter 'hccid' as shown below. Seems like the validation is not working for me. Can some one see what I am missing? const fastify = requi

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 where id is the param accessible request.params.id
  • /api/garage/:plate where plate is the param accessible at request.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 where color and size are the two querystrings accessible at request.query.color or request.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 or query: 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"