为什么自定义关键字验证后 validate.errors 为空?

Why is validate.errors empty after this custom keyword validation?

我正在使用一对自定义关键字来满足我们的验证需求。到目前为止,它在任何地方都运行良好......但现在我没有让错误持续存在并在验证后被检测到。

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。我希望验证失败,但是在一天结束时它说它通过了。对我做错了什么有什么想法吗?

注意:如果我将架构 batchitems 的定义更改为 type: 'integer',它会按预期失败。

事实证明,如果您在模式中除了 customValidator 之外还指定 type: 'string',它会起作用:

{
    type: 'object',
    required: [
        'requiredFieldName',
    ],
    properties: {
        requiredFieldName: {
            batch: {
                items: { type: 'string', customValidator: ['allowedType'] },
                limit: 100,
            },
        },
        optionalFields: { customValidator: ['allowedType1', 'allowedType2'] },
    },
}

不知道为什么,但现在可以了。