Search code examples
node.jsjsonschemaajvfastify

fastify schema validation with trim


I have written a schema as follows

input: {
            type: "string",
            allOf: [
                {
                  transform: [
                    "trim"
                  ]
                },
                {
                  minLength: 1
                }
            ],
            transform: ["trim"],
            trim: true,
            description: "Input",
            minLength: 1,
            maxLength: 3
        }

I want to accomplish 2 things - I want to trim the input and I want to validate that the trimmed input has minLength = 1. I tried all the different configurations I came across for doing this, but none of them have worked so far. I am using fastify version 3.0.0, and I believe it uses ajv validator for doing the transform and validation. The validation part is working, however the trim has not happened.


Solution

  • transform is not a standard json-schema feature.

    So you need to configure ajv to get it working:

    Notice that allOf array is executed sequentially, so if you move the min/max keyword at the root document, the spaces will be evaluated!

    
    const Fastify = require('fastify')
    const fastify = Fastify({
      logger: true,
      ajv: {
        plugins: [
          [require('ajv-keywords'), ['transform']]
        ]
      }
    })
    
    fastify.post('/', {
      handler: async (req) => { return req.body },
      schema: {
        body: {
          type: 'object',
          properties: {
            input: {
              type: 'string',
              allOf: [
                { transform: ['trim'] },
                { minLength: 1 },
                { maxLength: 3 }
              ]
            }
          }
        }
      }
    })
    
    fastify.inject({
      method: 'POST',
      url: '/',
      payload: {
        input: '   foo   '
      }
    }, (_, res) => {
      console.log(res.payload);
    })