【发布时间】:2019-06-18 19:15:50
【问题描述】:
我正在使用一对自定义关键字来缓解我们的验证需求。到目前为止,它在所有地方都运行良好......但现在我没有让错误持续存在并在验证后被检测到。
ajv.addKeyword('batch', {
compile: function validator(batch) {
const { limit, items } = batch;
const arraySchema = {
type: 'array',
items,
minItems: 1,
maxItems: limit,
};
return ajv.compile({
oneOf: [
arraySchema,
items,
],
});
},
errors: false,
});
ajv.addKeyword('customValidator', {
type: 'string',
validate: function validate(schema, data) {
try {
if (data.length > 500) {
throw new Error('should be <= 500 characters');
}
const { type } = myCustomValidator.parse(data);
if (schema === true || schema.includes(type)) {
return true;
}
throw new TypeError(`${data} must be one of the following: ${schema}`);
} catch (error) {
if (!validate.errors) {
validate.errors = [];
}
validate.errors.push(error);
return false;
}
},
errors: true,
});
然后是这样的架构:
{
type: 'object',
required: [
'requiredFieldName',
],
properties: {
requiredFieldName: {
batch: {
items: { customValidator: ['allowedType'] },
limit: 100,
},
},
optionalFields: { customValidator: ['allowedType1', 'allowedType2'] },
},
}
然后我创建了一个测试失败,导致myCustomValidator.parse 抛出。
{
requiredFieldName: ['blah', 'blah'],
}
使用console.log,我可以看到它正在抛出并被捕获并被添加到validator.errors。我预计验证会失败,但最终它说它通过了。关于我做错了什么的任何想法?
注意:如果我将架构的batch 中items 的定义更改为type: 'integer',它将按预期失败。
【问题讨论】:
标签: javascript ajv