Paul Milham
Paul Milham

Reputation: 546

Fastify JSON Schema Default Value of `null`

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?

Upvotes: 0

Views: 5764

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 13150

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}' }

Upvotes: 3

Related Questions