【发布时间】:2022-01-24 01:12:34
【问题描述】:
几个月以来,我一直在使用 AJV 进行验证。在 v6.x 上使用了一段时间,现在需要升级才能使格式和自定义错误消息正常工作。不幸的是,它似乎非常糟糕。我在错误报告和其他闲聊中找不到任何帮助。
包:
"ajv": "^8.8.2",
"ajv-errors": "^3.0.0",
"ajv-formats": "^2.1.1",
明确地说,我可以让它在 Express API 中正常工作,声明如下:
const Ajv = require("ajv");
const ajv = new Ajv({ allErrors: true, strict: false });
const ajvFormats = require("ajv-formats")(ajv);
const ajvErrors = require("ajv-errors")(ajv);
但是,我也在 React 项目中使用它,而这正是它令人讨厌的地方。声明如下:
import Ajv from "ajv";
import AjvFormats from "ajv-formats";
import AjvErrors from "ajv-errors";
const ajv = new Ajv({
allErrors: true,
strict: false,
strictTypes: false,
code: { optimize: false }
});
AjvErrors(ajv);
AjvFormats(ajv);
无论在 Ajv 构造函数中使用什么选项,都会产生以下错误:
TypeError: Cannot read properties of undefined (reading 'allErrors')
ajvErrors
src/index.ts:385
Module.<anonymous>
src/mod/validator.js:10
7 | strictTypes: false,
8 | code: { optimize: false }
9 | });
> 10 | AjvErrors(ajv);
11 | AjvFormats(ajv);
如果我注释掉 AjvErrors(ajv) 行以查看格式是否可以工作,我会得到一个单独且完全不同的 AjvFormats(ajv) 错误:
TypeError: Cannot read properties of undefined (reading 'code')
addFormats
src/index.ts:55
52 | if (items) {
53 | errors.items = {};
54 | for (let i = 0; i < items.length; i++)
> 55 | errors.items[i] = [];
| ^ 56 | }
57 | return errors;
58 | }
View compiled
formatsPlugin
src/index.ts:42
39 | const schMessage = typeof sch == "string" ? sch : sch._;
40 | if (schMessage)
41 | processAllErrors(schMessage);
> 42 | if (!options.keepErrors)
| ^ 43 | removeUsedErrors();
44 | });
45 | function childErrorsConfig({ properties, items }) {
View compiled
Module.<anonymous>
src/mod/validator.js:11
8 | code: { optimize: false }
9 | });
10 | // AjvErrors(ajv);
> 11 | AjvFormats(ajv);
12 |
13 | const initValidationCache = async () => {
14 | let { entityType, schema } = window;
我是 SOL 吗?这些项目死了吗?我在那里看到的错误报告中几乎没有活动。我已经投入了大量时间并围绕这个库编写了很多代码,作为我的验证库,因为它每月下载数千万次。看起来很安全!不是超级鼓舞人心。 :(
【问题讨论】:
标签: javascript json validation jsonschema ajv