Reputation: 5123
I am trying to generate pre compile standalone code like so:
https://ajv.js.org/standalone.html
I have an AJV instance created like so:
const ajv = require("ajv");
const add_formats = require("ajv-formats");
const add_errors = require("ajv-errors");
const ajv_inst = new ajv({
code: { source: true }, // needed for standalone pre compiled scripts
allErrors: true,
$data: true,
});
add_errors(add_formats(ajv_inst));
However, I have custom keywords defined like so:
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],
},
});
In order to generate the standalone code with custom keywords, I think the keyword needs to be defined with a code generator function instead of the validate
like so:
code(cxt: KeywordCxt) {
const {data, schema} = cxt
const op = schema ? _`!==` : _`===`
cxt.fail(_`${data} %2 ${op} 0`) // ... the only code change needed is to use `cxt.fail$data` here
},
https://ajv.js.org/keywords.html#define-keyword-with-validate-function
questions:
validate
property defined, is there a way to generate the pre compiled standalone code with the function defined as is in the validate
property?validate
function into the required code-gen code?Upvotes: 1
Views: 89