如何在Ajv中添加关键字Nullable(或allowNull)?

Khu*_*rob 2 node.js ajv

我写了下面的代码。

var ajv = new require('ajv');

ajv.addKeyword('allowNull', {
    type: 'null',
    metaSchema: {
        type: 'boolean'
    },
    compile: function(allowNullEnable, parentSchema) {
        return function(data, dataPath, parentData) {
            if (allowNullEnable) {
                return true;
            } else {
                if (parentSchema.type == 'null') {
                    return true;
                } else {
                    return data === null ? false : true;
                }
            }
        }
    }
});

var schema = {
  type: "object",
  properties: {
    file: {
      type: "string",
      allowNull: true
    }
  }
};

var data = {
   file: null
};

console.log(ajv.validate(schema, data)) // Expected true
Run Code Online (Sandbox Code Playgroud)

但这行不通。如何编写这样的验证器?

即使compile函数始终返回true,也不会通过验证。

可以在节点沙箱中测试代码:https : //runkit.com/khusamov/59965aea14454f0012d7fec0

esp*_*esp 5

您不能覆盖type关键字。null是JSON中的单独数据类型,因此您需要"type": ["string", "null"]在架构中使用,而无需使用自定义关键字。