Skip to content

Instantly share code, notes, and snippets.

@philippefutureboy
Created March 5, 2018 18:29
Show Gist options
  • Save philippefutureboy/7335eef43a887e41a80039fc073c23f6 to your computer and use it in GitHub Desktop.
Save philippefutureboy/7335eef43a887e41a80039fc073c23f6 to your computer and use it in GitHub Desktop.
ajv-oneOf
var AJV = require('ajv');
var schema = {
"properties": {
"name": { "type": "string" },
"type": { "type": "string" },
"constraints": {
"properties": {
"PRIMARY_KEY": { "type": "boolean" },
"FOREIGN_KEY": {
"oneOf": [
{
"properties": {
"tid": { "type": "string" },
"key": { "type": "string" }
},
"required": ["tid", "key"],
"additionalProperties": false
},
{ "type": "boolean" }
]
}
},
"additionalProperties": false
}
},
"additionalProperties": false
};
var values = [
{
"constraints": {
"FOREIGN_KEY": {
"tid": "d01",
"key": "FD01SUMKEY"
}
}
},
{
"constraints": {
"FOREIGN_KEY": false
}
}
];
var validate = function(schema, value) {
console.log("in");
try{
var ajv = new AJV();
}catch(e){
console.log(e);
}
var validated = ajv.validate(schema, value);
return validated ? 'Validated successfully' : `Validation failed: ${JSON.stringify(ajv.errors)}`;
};
console.log("Validating...");
console.log(validate(schema, values[0]));
console.log(validate(schema, values[1]));
console.log("Ran successfully");
{
"scripts": {
"start": "node index.js"
},
"dependencies": {
"ajv": "^6.2.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment