首页 > 解决方案 > 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'] 应该是对象,布尔值

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

标签: ajv

解决方案


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


推荐阅读