javascript - 使用 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);
});
解决方案
你看过文档吗?有以下片段可用:
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
它被视为一个额外的有效模式,它接受除空消息之外的所有内容。所以,我认为你不想传递true
给compile()
.
推荐阅读
- ios - SwiftUI 多个垂直列表行动画不起作用
- android - 事件将在 10 秒内从谷歌日历中删除:Android
- java - 必须使用此布局,如何打印成绩?
- javascript - 如何通过 JavaScript 中的对象数组和值数组创建新对象
- java - Java apache Tika 如何从 rar 获取文件?
- r - 在 R 中切割 3D 网格
- python - 如何像whatsapp一样通过qr授权?
- javascript - 将 JavaScript 对象数组传递给控制器
- objective-c - 如何通过编程专门创建模态表窗口
- mysql - Mysql LEFT JOIN 两次在不同的子表上使用相同的父主键