exframe-request-validator
v1.10.2
Published
Validates requests and returns pretty(ish) error messages
Downloads
1,629
Readme
exframe-request-validator
Wraps ajv to validate requests and produce human readable error messages when validation fails.
Example - validate requests
const validator = require('exframe-request-validator');
const sampleSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
title: 'Sample Validation Schema',
type: 'object',
required: [ 'thing1' ],
properties: {
thing1: { type: 'string' },
thing2: { type: 'string', minLength: 1 }
}
};
const validateSchema = (schema) => {
const validate = validator.generateValidator(schema);
return async (context, obj) => {
validate({ log: context.log }, obj);
};
};
return validateSchema(sampleSchema)(context, requestBody)
.then(()) => {
// Passed validation - do something awesome
}
.catch(err => {
// One or more things failed validation.
// err.status = 400
// err.message = Human readable message
// err.validationErrors = Array of validation failures
});
custom error messages can also be used against specific properties / items use https://github.com/epoberezkin/ajv-errors for reference
Schema Dependencies
An optional second parameter can be passed to the generateValidator()
function.
It must be an array of schema dependencies which will be added via ajv.addSchema()
.
Each of these schemas must contain an $id.
More information about addSchema()
can be found here.
Example
const validate = validator.generateValidator(schema, [referenceSchema1, referenceSchema2]);