user3740951
user3740951

Reputation: 1239

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.

Upvotes: 0

Views: 2717

Answers (2)

Yogeshwar Tanwar
Yogeshwar Tanwar

Reputation: 417

Install ajv-keywords using below cmd

npm i ajv-keywords

Import 'ajvKeywords' in code as follows

import ajvKeywords from 'ajv-keywords'

Pass on ajv instance to ajvKeyword

const ajv = new Ajv({
    useDefaults: true,
  })


 ajvKeywords(ajv, ['transform'])

And use in schema as follows

schema: {
    body: {
      type: 'object',
      properties: {
        input: {
          type: 'string',
          transform: ['trim'],
          allOf: [
            { transform: ['trim'] },
            { minLength: 1 },
            { maxLength: 3 }
          ]
       }
        }
      }
    }
  }

Upvotes: 4

Manuel Spigolon
Manuel Spigolon

Reputation: 12870

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);
})

Upvotes: 1

Related Questions