ajv - AJV - 检查属性是一个函数
问题描述
我正在使用 AJV 检查“设置”对象。我想添加一个onFeedbackChange
可以作为函数的新属性(不是必需的)。
const ajv = new Ajv({
allErrors: true,
});
ajv.addKeyword('function', {
valid: true,
validate: function (data) {
return typeof data === 'function';
}
});
const validate = ajv.compile(settingsSchema);
架构:
feedback:
type: object
properties:
enabled:
type: boolean
saveFeedback: *endpoint
updateFeedback: *endpoint
onFeedbackChange: function
additionalProperties: false
required:
- enabled
- saveFeedback
- updateFeedback
但这失败了:
错误:架构无效:data.properties['modules'].properties['feedback'].properties['onFeedbackChange'] 应该是对象,布尔值
我想知道如何执行验证,以及为什么这不是内置的。
解决方案
我们使用它来验证包含 React 组件的数据:
我们正在验证的数据:
const config = {
id: 'dailyGraph',
component: BarGraph, // <-- react component (function)
type: 'bar',
...
}
我们的架构:
const barSchema = {
$schema: 'http://json-schema.org/draft-07/schema',
$id: 'dailyGraph',
type: 'object',
readOnly: true,
title: 'Schema for validating graph config',
properties: {
id: {
$id: '#/properties/id',
type: 'string'
},
component: {
$id: '#/properties/component',
instanceof: 'Function', // <-- ajv custom keyword
},
type: {
$id: '#/properties/type',
type: 'string',
enum: ['bar','pie'],
}
...
},
required: ['id', 'assays', 'graphType']
};
和.addKeyword
这里的语法:https ://github.com/epoberezkin/ajv/issues/147#issuecomment-199371370
const ajv = new Ajv();
const { id } = config;
const CLASSES = { Function: Function, ... };
ajv.addKeyword('instanceof', {
compile: schema => data => data instanceof CLASSES[schema]
});
ajv.validate(barSchema, config)
? res(true)
: console.error(`Graph config error for ${id}: ${ajv.errorsText()}`);
component
作为字符串(或除函数之外的任何内容)传递会抛出:Graph config error for dailyGraph: data.component should pass "instanceof" keyword validation
推荐阅读
- vba - Access 2007 VBA - 打开两个 Excel 工作簿
- ios - Apple Watch 强制触控菜单
- javascript - 使用 Javascript、HTML、JQuery 和 CSS 如何根据 HTML Select OnChange 设置变量,进行计算并立即更新?
- android - 询问关于Json序列化的问题
- html - 输入表单对齐不正确
- javascript - 当 onchange 做 php 时 onkeyup 不工作
- javascript - 如何将 React 组件添加到现有的 Django 项目
- python - 如何将python添加到CMD?
- c# - 如何通过 C# 从 000000-999999 开始仅打印 6 位数字?
- matlab - 如何通过 for 循环(没有矢量化公式)为多个变量开发梯度下降?