首页 > 解决方案 > 使用 Ajv.js 一次编译多个 json 模式

问题描述

我一直在寻找一种方法来一次用 ajv(另一个 JSON 模式验证器)编译多个 json 模式。我尝试了以下方法并且它有效(下面的代码示例)但我不确定它是否是正确的方法,因为根据此处的 ajv API https://www.npmjs.com/package/ajv#api

函数编译定义为 .compile(Object schema) -> Function

这个定义没有提到接受布尔值作为参数,但是当我尝试ajv.compile()不带任何参数使用时,我得到了这个错误:

错误:架构应该是对象或布尔值

但是在调用ajv.compile(true)代码后运行没有任何错误,我猜true作为参数传递意味着编译选项中定义的所有模式,但正如我所说,我在 avs 文档中找不到关于我的这个假设的任何信息。(我在 schemas.js 文件中定义了我的模式)

这是编译多个模式的正确方法吗?

var express = require('express');
var router = express.Router();

const schemas = require('../schemas.js');

var Ajv = require('ajv');
var ajv = new Ajv({
    allErrors: true,
    schemas: [schemas.profile, schemas.vzor]
});

var validate = ajv.compile(true);

router.post('/schema_test/', function (req, res, next) {

    var valid = ajv.validate('profile', req.body);
    if (valid) 
        console.log('Valid!');
    else
        console.log('Invalid: ' + ajv.errorsText(validate.errors));

    return res.sendStatus(200);
});

标签: javascriptnode.jsexpressjsonschemaajv

解决方案


你看过文档吗?有以下片段可用:

var schema = {
  "$id": "http://example.com/schemas/schema.json",
  "type": "object",
  "properties": {
    "foo": { "$ref": "defs.json#/definitions/int" },
    "bar": { "$ref": "defs.json#/definitions/str" }
  }
};

var defsSchema = {
  "$id": "http://example.com/schemas/defs.json",
  "definitions": {
    "int": { "type": "integer" },
    "str": { "type": "string" }
  }
};

var ajv = new Ajv;
var validate = ajv.addSchema(defsSchema)
                  .compile(schema);

我相信当您调用ajv.compile(true),时,true它被视为一个额外的有效模式,它接受除空消息之外的所有内容。所以,我认为你不想传递truecompile().


推荐阅读