aboutsummaryrefslogtreecommitdiff
path: root/dev/schema-validate.js
diff options
context:
space:
mode:
authortoasted-nutbread <toasted-nutbread@users.noreply.github.com>2022-05-16 20:09:38 -0400
committerGitHub <noreply@github.com>2022-05-16 20:09:38 -0400
commit5a723034b8ac9eb86854bdcb16f624d18fa17178 (patch)
tree3c33468b7e93c779b0010b92ac88a230222ee33d /dev/schema-validate.js
parent84c9231a5e9733a6300d2edf1718b520467d7dc5 (diff)
Dictionary validate updates (#2137)
* Reuse JsomSchema instance * Install ajv * Add support for using ajv as a JSON schema validator * Update usage
Diffstat (limited to 'dev/schema-validate.js')
-rw-r--r--dev/schema-validate.js41
1 files changed, 39 insertions, 2 deletions
diff --git a/dev/schema-validate.js b/dev/schema-validate.js
index 2f0e2090..1a69ca48 100644
--- a/dev/schema-validate.js
+++ b/dev/schema-validate.js
@@ -27,17 +27,49 @@ vm.execute([
]);
const JsonSchema = vm.get('JsonSchema');
+class JsonSchemaAjv {
+ constructor(schema) {
+ const Ajv = require('ajv');
+ const ajv = new Ajv({
+ meta: false,
+ strictTuples: false,
+ allowUnionTypes: true
+ });
+ ajv.addMetaSchema(require('ajv/dist/refs/json-schema-draft-07.json'));
+ this._validate = ajv.compile(schema);
+ }
+
+ validate(data) {
+ if (this._validate(data)) { return; }
+ const {errors} = this._validate(data);
+ const message = errors.map((e) => e.toString()).join('\n');
+ throw new Error(message);
+ }
+}
+
+function createJsonSchema(mode, schema) {
+ switch (mode) {
+ case 'ajv': return new JsonSchemaAjv(schema);
+ default: return new JsonSchema(schema);
+ }
+}
function main() {
const args = process.argv.slice(2);
if (args.length < 2) {
console.log([
'Usage:',
- ' node schema-validate <schema-file-name> <data-file-names>...'
+ ' node schema-validate [--ajv] <schema-file-name> <data-file-names>...'
].join('\n'));
return;
}
+ let mode = null;
+ if (args[0] === '--ajv') {
+ mode = 'ajv';
+ args.splice(0, 1);
+ }
+
const schemaSource = fs.readFileSync(args[0], {encoding: 'utf8'});
const schema = JSON.parse(schemaSource);
@@ -47,7 +79,7 @@ function main() {
console.log(`Validating ${dataFileName}...`);
const dataSource = fs.readFileSync(dataFileName, {encoding: 'utf8'});
const data = JSON.parse(dataSource);
- new JsonSchema(schema).validate(data);
+ createJsonSchema(mode, schema).validate(data);
const end = performance.now();
console.log(`No issues detected (${((end - start) / 1000).toFixed(2)}s)`);
} catch (e) {
@@ -60,3 +92,8 @@ function main() {
if (require.main === module) { main(); }
+
+
+module.exports = {
+ createJsonSchema
+};