You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带自定义关键字的AJV独立验证代码预编译问题

带自定义关键字的AJV独立验证代码预编译问题

我正尝试生成预编译的AJV独立验证代码,目前已经创建了这样的AJV实例:

const ajv = require("ajv");
const add_formats = require("ajv-formats");
const add_errors = require("ajv-errors");
const ajv_inst = new ajv({
  code: { source: true }, // 生成独立预编译脚本的必要配置
  allErrors: true,
  $data: true,
});
add_errors(add_formats(ajv_inst));

同时我还定义了一个自定义关键字:

ajv_inst.addKeyword({
  keyword: "custom_array",
  validate: (schema, data) => {
    try {
      const unique_name = data.map((tar) => {
        return tar.name.toLowerCase().replaceAll(/\s+/g, "");
      });
      const unique_id = data.map((tar) => {
        return tar._id;
      });
      return (
        new Set(unique_name).size === data.length &&
        new Set(unique_id).size === data.length
      );
    } catch (err) {
      return false;
    }
  },
  metaSchema: {
    enum: [true],
  },
});

我了解到要生成包含自定义关键字的独立代码,关键字需要通过代码生成器函数定义,而不是使用validate属性,示例写法类似这样:

code(cxt: KeywordCxt) {
  const {data, schema} = cxt
  const op = schema ? _`!==` : _`===`
  cxt.fail(_`${data} %2 ${op} 0`) // ... 这里只需把`cxt.fail$data`改为`cxt.fail`即可
},

我有两个问题:

  1. 既然我已经通过validate属性定义了验证逻辑,有没有办法直接基于这个已有的validate函数生成预编译的独立代码?
  2. 如果上述方法不可行,有没有简单或自动化的方式,把我的validate函数转换成符合要求的代码生成器代码?

备注:内容来源于stack exchange,提问作者Bear Bile Farming is Torture

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 17:59:36