Created
October 16, 2018 12:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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