AJV doesn't validate my body with the function returned by compile

1.3k views Asked by At

I'm building an API with express and I use AJV as a middleware to validate the body which is sent.

I'm using AJV 6.12.6

This is my schema in JSON body-foobar.json:

{
  "type": "object",
  "properties": {
    "foobar": {
      "type": "string"
    }
  },
  "required": ["foobar"]
}

Here the way I use the middleware:

const validator = require('../../middleware/validator')
const schema = require('../../middleware/schema/body-foobar.json')
...

router.post('/foo', validator(schema, 'body'), post.handler)

And finally my middleware:

const Ajv = require('ajv')


module.exports = (schema, data) => {
  const ajv = new Ajv()
  const validate = ajv.compile(schema)

  return (req, res, next) => {
    const validation = validate(schema, req[data])

    if (!validation) {
      return res.status(400).json({success: validation, error: validate.errors[0].message})
    }
    return next()
  }
}

With this code, AJV never validates my body and says that foobar is missing but there is, if I remove the required parameter it works but if I put a number instead of a string for the param foobar it will validate my body...

To make it works as expected, I have to not call the function returned by compile but call:

ajv.validate(schema, req[data])

This way, it makes the compile function useless, and I'm afraid of performances (cached, or compile for each request). Did I make a mistake by using the function returned by compile? How can I make it works this way? Because it's super weird that it works well one way but not the other ...

Thank you for your help

1

There are 1 answers

0
Raphael On BEST ANSWER

The function returned by compile has different parameters than ajv.validate and no need de specify the schema.

I just need to call: validate(req[data] and it's working fine.