【问题标题】:AJV - Check property is a functionAJV - 检查属性是一个函数
【发布时间】:2020-02-12 20:45:53
【问题描述】:

我正在使用 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'] 应该是对象,布尔值

我想知道如何执行验证,以及为什么这不是内置的。

【问题讨论】:

标签: ajv


【解决方案1】:

我们使用它来验证包含 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

【讨论】:

  • 我还没有测试过,但它看起来不错,和我当时想做的非常相似! :)
  • 希望对您有所帮助。最初让我陷入循环的是.addKeyword 循环内的schema 不应根据您的验证模式命名。一旦我弄清楚了列出的票证中的示例-一切正常。
  • 这也适用于 ajv v8 const classes = {Function: Function}; ajv.addKeyword({keyword: 'instanceof', schemaType: 'string', validate (schema, data) { return data instanceof classes[schema] }})
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多