【问题标题】:JS Json Schema - AJVJS Json 架构 - AJV
【发布时间】:2018-09-13 23:30:02
【问题描述】:

我正在使用 AJV(JS JSON Schema Validator),并且正在尝试找到一种方法来扩展它支持的类型。

我收到此错误是因为在架构中我有一个自定义类型(我在 python 中验证的 DocumentReference - jsonschema 也是如此)

Error: schema is invalid: data.properties['allow'].properties['custom_signature'].type should be equal to one of the allowed values, data.properties['allow'].properties['custom_signature'].type[0] should be equal to one of the allowed values, data.properties['allow'].properties['custom_signature'].type should match some schema in anyOf
    at Ajv.validateSchema (ajv.js?ea76:183)
    at Ajv._addSchema (ajv.js?ea76:312)
    at Ajv.compile (ajv.js?ea76:112)
    at eval (configs.js?76ed:66)

这是架构的一个小示例:

"custom_signature": {
    "type": [
        "DocumentReference",
        "object",
        "null"
    ]
},

在 python jsonschema 中有一种方法可以扩展类型并定义您希望如何验证它们,在 AJV 中是否有一些等价物?

var json = {
  "type": "object",
  "properties": {
    "custom_signature": {
      "type": [
        "DocumentReference",
        "null",
        "object"
      ]
    }
  }
};

const ajv = new Ajv({
  allErrors: true
});
console.log(ajv);
const validate = ajv.compile(json);
console.log(validate({'custom_signature': {}}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/6.4.0/ajv.min.js"></script>

JSFiddle

【问题讨论】:

  • 我个人没用过AJV,但是看错误,能不能别把"custom_signature"加到data.properties['allow']上?
  • 基本draft07包含以下类型:“array”、“boolean”、“integer”、“null”、“number”、“object”、“string” 我想扩展这些,在错误,它表示 type[0] 不是已知值之一
  • 您能否提供更多源代码,我可能找到了解决您问题的方法,但我不确定 100% 确定您的源代码的作用自动取款机。
  • 当我尝试这个时,它工作正常吗? - JSFiddle
  • json 架构看起来应该与您所做的不同 JSFiddle

标签: javascript ajv


【解决方案1】:

我刚刚制作了一个模块来简化一些 AJV 问题。它还包括一个名为 .addType() 的新函数:

Github:https://github.com/webarthur/super-ajv

NPM:https://www.npmjs.com/package/super-ajv

const ajv = new Ajv()

ajv.addType('mongoid', {
  compile: function () {
    return function (data) {
      const re = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i
      return re.test(data)
    }
  }
})

const schema = {
  properties: {
    user_id: { type: 'mongoid' }
  }
}

您还可以:

const schema = {
  properties: {
    '*name': 'string',
    '*email': 'email',
    'age': 'number',
    '*message': 'string',
  }
}

享受吧!

【讨论】:

    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2021-12-05
    • 2019-11-19
    • 2021-06-06
    • 2016-08-23
    相关资源
    最近更新 更多