我正在使用 AJV 根據架構驗證 HTTP 請求有效負載。但是,我看到一個錯誤報告,這是我沒想到的。這是一個演示問題的代碼示例:
const schema = {
type: 'array',
minItems: 1,
items: {
anyOf: [
{
type: 'object',
properties: {
op: {
enum: ['replace']
},
path: {
type: 'string',
pattern: '/data/to/foo/bar',
},
value: {
type: 'string',
},
},
},{
type: 'object',
properties: {
op: {
enum: ['replace']
},
path: {
type: 'string',
pattern: '/data/to/baz',
},
value: {
type: 'object',
required: ['foo', 'bar'],
properties: {
foo: {
type: 'string',
},
bar: {
type: 'string',
},
}
}
}
}
],
},
}
const validator = new ajv()
const compiledValidator = validator.compile(schema)
const data = [
{ // this object should pass
op: 'replace',
path: '/data/to/foo/bar',
value: 'foo',
},
{ // this object should fail in the `value` mismatch (missing required attribute)
op: 'replace',
path: '/data/to/baz',
value: {
foo: 'bar',
},
},
]
compiledValidator(data)
console.log(compiledValidator.errors)
該模式定義了傳入資料物件串列應與之匹配的多個物件。第一個資料項與模式匹配(第一項模式),但是第二個資料項缺少物件中的必需屬性 ( bar) value。
當我運行上面的代碼時,我得到以下輸出:
[
{
instancePath: '/1/path',
schemaPath: '#/items/anyOf/0/properties/path/pattern',
keyword: 'pattern',
params: { pattern: '/data/to/foo/bar' },
message: 'must match pattern "/data/to/foo/bar"'
},
{
instancePath: '/1/value',
schemaPath: '#/items/anyOf/1/properties/value/required',
keyword: 'required',
params: { missingProperty: 'bar' },
message: "must have required property 'bar'"
},
{
instancePath: '/1',
schemaPath: '#/items/anyOf',
keyword: 'anyOf',
params: {},
message: 'must match a schema in anyOf'
}
]
我理解第二個和第三個(最后一個)錯誤。但是,第一個錯誤似乎表明與第一項架構的要求path不匹配path。確實,第二個資料項與第一個架構項不匹配,但我似乎不明白它是如何相關的。我認為錯誤將集中在value,而不是 ,path因為它與path模式匹配。
有沒有辦法讓錯誤報告更集中在重要的錯誤上?
uj5u.com熱心網友回復:
評估器無法知道您是打算匹配第一個“anyOf”子模式還是第二個,因此最有用的做法是向您顯示所有錯誤。
這可能會令人困惑,因為您不需要解決所有錯誤,只需解決其中的一些錯誤,這就是為什么某些實作還提供分層錯誤格式以更容易查看此類關系的原因。也許如果您要求ajv實作更多這些錯誤格式,它就會發生:)
uj5u.com熱心網友回復:
通過查看instancePath每個錯誤的 ,您可以看到所有錯誤都與資料中的第二項有關,所有錯誤都以開頭/1。這是資料中產生錯誤的位置。
因此,讓我們看一下第二項并將其與模式進行比較。
{ // this object should fail in the `value` mismatch (missing required attribute)
op: 'replace',
path: '/data/to/baz',
value: {
foo: 'bar',
},
}
該架構表示一個專案應該(來自anyOf)具有
path: '/data/to/foo/bar'和value: { type: 'string' }, 或path: '/data/to/baz'和value: { required: [ 'foo', 'bar' ] }
報告的錯誤是:
- 第一種情況失敗,因為
path是錯誤的。 - 第二種情況失敗,因為
/value/bar不存在。 - 最后一個錯誤只是
anyOf報告沒有任何選項通過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368094.html
標籤:节点.js jsonschema 艾维
