Skip to content

Instantly share code, notes, and snippets.

@jcpst
Created October 16, 2018 12:33
Show Gist options
  • Save jcpst/5e17c7454203ed04c96a5f2750219a8a to your computer and use it in GitHub Desktop.
Save jcpst/5e17c7454203ed04c96a5f2750219a8a to your computer and use it in GitHub Desktop.
Takes an array of json schemas and returns an object with middleware to validate requests
const Ajv = require('ajv');
function errFormat(obj) {
return ({ dataPath, message }) =>
`Type Error: '${obj.schema.title}${dataPath}' ${message}.\n`;
}
function validator(ajvOptions = {}) {
return (acc, schema) =>
Object.assign(acc, {
[schema.title]: (ctx, next) => {
const ajv = new Ajv(ajvOptions);
const validate = ajv.compile(schema);
const valid = validate(ctx.request.body);
if (!valid) {
const msg = errFormat(validate);
ctx.throw(400, 'validation error', msg);
}
next();
}
});
}
module.exports = ajvOptions => schemas =>
schemas.reduce(validator(ajvOptions), {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment