0

I'm using Fastify v2 with the built in AJV JSON Schema validator. I'm pulling some data from another service and sometimes fields are present, sometimes not. That's fine, but if the field is undefined, I'd like to default it to null instead of leaving it undefined because I'm relying on the keys of the object being present.

Example:

module.exports = {
  $id: "transaction",
  type: "object",
  required: [
    "txnDate",
  ],
  properties: {
    txnDate: {type: ["integer", "null"], minimum: 0, default: null},
  },
};

Fastify is throwing TypeError: Cannot use 'in' operator to search for 'anyOf' in null when I attempt to set the default value in this way. Is there a way to get the behavior I want in Fastify using AJV?

Paul Milham
  • 526
  • 5
  • 13

1 Answers1

2

You can try with this working snippet with Fastify 2.7.1 since nullable is supported thanks to AJV:

const Fastify = require('fastify')
const fastify = Fastify({ logger: false })
fastify.post('/', {
    schema: {
        body: {
            $id: "transaction",
            type: "object",
            required: ["txnDate"],
            properties: {
                txnDate: { type: 'number', nullable: true, minimum: 0, default: null },
            },
        }
    }
}, (req, res) => { res.send(req.body) })

fastify.inject({
    method: 'POST',
    url: '/',
    payload: {}
}, (err, res) => {
    console.log({ err, res: res.payload });
})

Will print out:

{ err: null, res: '{"txnDate":null}' }

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
  • I updated from 2.3.0 to 2.7.1 and the program works as you've shown above. Thank you for the thorough answer. Of note, using 2.3.0 with the above code, the default value is 0, not null which is weird. – Paul Milham Aug 27 '19 at 19:31
  • 1
    the nullable option has been released in 2.6.0 https://github.com/fastify/fastify/releases/tag/v2.6.0 – Manuel Spigolon Aug 28 '19 at 07:22