3 var util = require('./_util');
5 module.exports = function defFunc(ajv) {
6 if (!ajv._opts.$data) {
7 console.warn('keyword select requires $data option');
10 var metaSchemaRef = util.metaSchemaRef(ajv);
11 var compiledCaseSchemas = [];
13 defFunc.definition = {
14 validate: function v(schema, data, parentSchema) {
15 if (parentSchema.selectCases === undefined)
16 throw new Error('keyword "selectCases" is absent');
17 var compiled = getCompiledSchemas(parentSchema, false);
18 var validate = compiled.cases[schema];
19 if (validate === undefined) validate = compiled.default;
20 if (typeof validate == 'boolean') return validate;
21 var valid = validate(data);
22 if (!valid) v.errors = validate.errors;
26 metaSchema: { type: ['string', 'number', 'boolean', 'null'] }
29 ajv.addKeyword('select', defFunc.definition);
30 ajv.addKeyword('selectCases', {
31 compile: function (schemas, parentSchema) {
32 var compiled = getCompiledSchemas(parentSchema);
33 for (var value in schemas)
34 compiled.cases[value] = compileOrBoolean(schemas[value]);
35 return function() { return true; };
40 additionalProperties: metaSchemaRef
43 ajv.addKeyword('selectDefault', {
44 compile: function (schema, parentSchema) {
45 var compiled = getCompiledSchemas(parentSchema);
46 compiled.default = compileOrBoolean(schema);
47 return function() { return true; };
50 metaSchema: metaSchemaRef
55 function getCompiledSchemas(parentSchema, create) {
57 compiledCaseSchemas.some(function (c) {
58 if (c.parentSchema === parentSchema) {
63 if (!compiled && create !== false) {
65 parentSchema: parentSchema,
69 compiledCaseSchemas.push(compiled);
74 function compileOrBoolean(schema) {
75 return typeof schema == 'boolean'
77 : ajv.compile(schema);