Validation and Serialization

Fastify uses a schema-based approach, and even if it is not mandatory we recommend using JSON Schema to validate your routes and serialize your outputs. Internally, Fastify compiles the schema into a highly performant function.

Validation

The route validation internally relies upon Ajv, 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 or a PUT.
  • querystring: validates the query string. This can be a complete JSON Schema object (with a type property of 'object' and a 'properties' object containing parameters) or a simpler variation in which the type and properties attributes are forgone and the query parameters are listed at the top level (see the example below).
  • params: validates the route params.
  • headers: validates the request headers.
    Example:
  1. const schema = {
  2. body: {
  3. type: 'object',
  4. properties: {
  5. someKey: { type: 'string' },
  6. someOtherKey: { type: 'number' }
  7. }
  8. },
  9. querystring: {
  10. name: { type: 'string' },
  11. excitement: { type: 'integer' }
  12. },
  13. params: {
  14. type: 'object',
  15. properties: {
  16. par1: { type: 'string' },
  17. par2: { type: 'number' }
  18. }
  19. },
  20. headers: {
  21. type: 'object',
  22. properties: {
  23. 'x-foo': { type: 'string' }
  24. },
  25. required: ['x-foo']
  26. }
  27. }
  28. fastify.post('/the/url', { schema }, handler)

Note that Ajv will try to coerce the values to the types specified in your schema type keywords, both to pass the validation and to use the correctly typed data afterwards.

Adding a shared schema

Thanks to the addSchema API, you can add multiple schemas to the Fastify instance and then reuse them in multiple parts of your application. As usual, this API is encapsulated.

  1. const fastify = require('fastify')()
  2. fastify.addSchema({
  3. $id: 'greetings',
  4. type: 'object',
  5. properties: {
  6. hello: { type: 'string' }
  7. }
  8. })
  9. fastify.route({
  10. method: 'POST',
  11. url: '/',
  12. schema: {
  13. body: 'greetings#'
  14. },
  15. handler: () => {}
  16. })
  17. fastify.register((instance, opts, next) => {
  18. /**
  19. * In children's scope can use schemas defined in upper scope like 'greetings'.
  20. * Parent scope can't use the children schemas.
  21. */
  22. instance.addSchema({
  23. $id: 'framework',
  24. type: 'object',
  25. properties: {
  26. fastest: { type: 'string' },
  27. hi: 'greetings#'
  28. }
  29. })
  30. instance.route({
  31. method: 'POST',
  32. url: '/sub',
  33. schema: {
  34. body: 'framework#'
  35. },
  36. handler: () => {}
  37. })
  38. next()
  39. })

You can use the shared schema everywhere, as top level schema or nested inside other schemas:

  1. const fastify = require('fastify')()
  2. fastify.addSchema({
  3. $id: 'greetings',
  4. type: 'object',
  5. properties: {
  6. hello: { type: 'string' }
  7. }
  8. })
  9. fastify.route({
  10. method: 'POST',
  11. url: '/',
  12. schema: {
  13. body: {
  14. type: 'object',
  15. properties: {
  16. greeting: 'greetings#',
  17. timestamp: { type: 'number' }
  18. }
  19. }
  20. },
  21. handler: () => {}
  22. })

Retrieving a copy of shared schemas

The function getSchemas returns the shared schemas available in the selected scope:

  1. fastify.addSchema({ $id: 'one', my: 'hello' })
  2. fastify.get('/', (request, reply) => { reply.send(fastify.getSchemas()) })
  3. fastify.register((instance, opts, next) => {
  4. instance.addSchema({ $id: 'two', my: 'ciao' })
  5. instance.get('/sub', (request, reply) => { reply.send(instance.getSchemas()) })
  6. instance.register((subinstance, opts, next) => {
  7. subinstance.addSchema({ $id: 'three', my: 'hola' })
  8. subinstance.get('/deep', (request, reply) => { reply.send(subinstance.getSchemas()) })
  9. next()
  10. })
  11. next()
  12. })

This example will returns:

URL Schemas
/ one
/sub one, two
/deep one, two, three

Schema Compiler

The schemaCompiler is a function that returns a function that validates the body, url parameters, headers, and query string. The default schemaCompiler returns a function that implements the ajv validation interface. Fastify uses it internally to speed the validation up.

Fastify's baseline ajv configuration is:

  1. {
  2. removeAdditional: true, // remove additional properties
  3. useDefaults: true, // replace missing properties and items with the values from corresponding default keyword
  4. coerceTypes: true, // change data type of data to match type keyword
  5. allErrors: true // check for all errors
  6. }

This baseline configuration cannot be modified. If you want to change or set additional config options, you will need to create your own instance and override the existing one like:

  1. const fastify = require('fastify')()
  2. const Ajv = require('ajv')
  3. const ajv = new Ajv({
  4. // the fastify defaults (if needed)
  5. removeAdditional: true,
  6. useDefaults: true,
  7. coerceTypes: true,
  8. allErrors: true
  9. // any other options
  10. // ...
  11. })
  12. fastify.setSchemaCompiler(function (schema) {
  13. return ajv.compile(schema)
  14. })

But maybe you want to change the validation library. Perhaps you like Joi. In this case, you can use it to validate the url parameters, body, and query string!

  1. const Joi = require('joi')
  2. fastify.post('/the/url', {
  3. schema: {
  4. body: Joi.object().keys({
  5. hello: Joi.string().required()
  6. }).required()
  7. },
  8. schemaCompiler: schema => data => Joi.validate(data, schema)
  9. }, handler)

In that case the function returned by schemaCompiler returns an object like:

  • error: filled with an instance of Error or a string that describes the validation error
  • value: the coerced value that passed the validation

Serialization

Usually you will send your data to the clients via JSON, and Fastify has a powerful tool to help you, fast-json-stringify, which is used if you have provided an output schema in the route options. We encourage you to use an output schema, as it will increase your throughput by 100-400% depending on your payload and will prevent accidental disclosure of sensitive information.

Example:

  1. const schema = {
  2. response: {
  3. 200: {
  4. type: 'object',
  5. properties: {
  6. value: { type: 'string' },
  7. otherValue: { type: 'boolean' }
  8. }
  9. }
  10. }
  11. }
  12. fastify.post('/the/url', { schema }, handler)

As you can see, the response schema is based on the status code. If you want to use the same schema for multiple status codes, you can use '2xx', for example:

  1. const schema = {
  2. response: {
  3. '2xx': {
  4. type: 'object',
  5. properties: {
  6. value: { type: 'string' },
  7. otherValue: { type: 'boolean' }
  8. }
  9. },
  10. 201: {
  11. type: 'object',
  12. properties: {
  13. value: { type: 'string' }
  14. }
  15. }
  16. }
  17. }
  18. fastify.post('/the/url', { schema }, handler)

If you need a custom serializer in a very specific part of your code, you can set one with reply.serializer(…).

Error Handling

When schema validation fails for a request, Fastify will automtically return a status 400 response including the result from the validator in the payload. As an example, if you have the following schema for your route

  1. const schema = {
  2. body: {
  3. type: 'object',
  4. properties: {
  5. name: { type: 'string' }
  6. },
  7. required: ['name']
  8. }
  9. }

and fail to satisfy it, the route will immediately return a response with the following payload

  1. {
  2. "statusCode": 400,
  3. "error": "Bad Request",
  4. "message": "body should have required property 'name'"
  5. }

If you want to handle errors inside the route, you can specify the attachValidation option for your route. If there is a validation error, the validationError property of the request will contain the Error object with the raw validation result as shown below

  1. const fastify = Fastify()
  2. fastify.post('/', { schema, attachValidation: true }, function (req, reply) {
  3. if (req.validationError) {
  4. // `req.validationError.validation` contains the raw validation error
  5. reply.code(400).send(req.validationError)
  6. }
  7. })

You can also use setErrorHandler to define a custom response for validation errors such as

  1. fastify.setErrorHandler(function (error, request, reply) {
  2. if (error.validation) {
  3. reply.status(422).send(new Error('validation failed'))
  4. }
  5. })

Resources

原文: https://www.fastify.io/docs/v2.0.x/Validation-and-Serialization