feat: extract method to validate custom keyword definition

master
Evgeny Poberezkin 2019-02-22 11:16:30 +00:00
parent 187e0212bd
commit 6831b68f64
3 changed files with 35 additions and 6 deletions

10
lib/ajv.d.ts vendored
View File

@ -122,6 +122,14 @@ declare namespace ajv {
*/
removeKeyword(keyword: string): Ajv;
/**
* Validate keyword
* @this Ajv
* @param {object} definition keyword definition object
* @param {boolean} throwError true to throw exception if definition is invalid
* @return {boolean} validation result
*/
validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean;
/**
* Convert array of error message objects to string
* @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {object} options optional options with properties `separator` and `dataVar`.
@ -219,6 +227,8 @@ declare namespace ajv {
metaSchema?: object;
// schema: false makes validate not to expect schema (ValidateFunction)
schema?: boolean;
statements?: boolean;
dependencies?: Array<string>;
modifying?: boolean;
valid?: boolean;
// one and only one of the following properties should be present

View File

@ -30,6 +30,7 @@ var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;

View File

@ -7,7 +7,8 @@ var metaSchema = require('./refs/json-schema-draft-07.json');
module.exports = {
add: addKeyword,
get: getKeyword,
remove: removeKeyword
remove: removeKeyword,
validate: validateKeyword
};
var definitionSchema = {
@ -61,11 +62,7 @@ function addKeyword(keyword, definition) {
throw new Error('Keyword ' + keyword + ' is not a valid identifier');
if (definition) {
this.validateKeyword = this.validateKeyword
|| this.compile(definitionSchema, true);
if (!this.validateKeyword(definition))
throw new Error('custom keyword definition is invalid: ' + this.errorsText(this.validateKeyword.errors));
this.validateKeyword(definition, true);
var dataType = definition.type;
if (Array.isArray(dataType)) {
@ -158,3 +155,24 @@ function removeKeyword(keyword) {
}
return this;
}
/**
* Validate keyword definition
* @this Ajv
* @param {Object} definition keyword definition object.
* @param {Boolean} throwError true to throw exception if definition is invalid
* @return {boolean} validation result
*/
function validateKeyword(definition, throwError) {
validateKeyword.errors = null;
var v = this._validateKeyword = this._validateKeyword
|| this.compile(definitionSchema, true);
if (v(definition)) return true;
validateKeyword.errors = v.errors;
if (throwError)
throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
else
return false;
}