【问题标题】:Fastify JSON Schema Default Value of `null`Fastify JSON Schema 默认值 `null`
【发布时间】:2019-08-21 15:16:26
【问题描述】:

我正在使用带有内置 AJV JSON Schema 验证器的 Fastify v2。我正在从另一个服务中提取一些数据,有时字段存在,有时不存在。这很好,但如果该字段未定义,我想将其默认为 null 而不是未定义,因为我依赖于存在的对象的键。

例子:

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

当我尝试以这种方式设置默认值时,Fastify 正在抛出 TypeError: Cannot use 'in' operator to search for 'anyOf' in null。有没有办法使用 AJV 在 Fastify 中获得我想要的行为?

【问题讨论】:

    标签: javascript node.js jsonschema ajv fastify


    【解决方案1】:

    由于 AJV 支持 nullable,你可以尝试在 Fastify 2.7.1 中使用这个有效的 sn-p:

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

    将打印出来:

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

    【讨论】:

    • 我从 2.3.0 更新到 2.7.1 并且该程序的工作方式如上所示。谢谢你的彻底回答。需要注意的是,上面的代码使用2.3.0,默认值为0,而不是null,这很奇怪。
    • 可空选项已在 2.6.0 中发布 github.com/fastify/fastify/releases/tag/v2.6.0
    猜你喜欢
    • 2015-11-26
    • 2011-06-16
    • 2010-12-07
    • 2013-10-19
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    相关资源
    最近更新 更多