pvmed-server-libs
Version:
pvmed server libs
45 lines (44 loc) • 1.29 kB
JavaScript
const router = require('koa-joi-router')
const Joi = router.Joi
const BadRequestError = require('../exceptions/bad_request_error')
module.exports = function(validateParts = {}, options = {}) {
return async (ctx, next) => {
for (let part in validateParts) {
const schema = validateParts[part]
let inputParams
switch (part) {
case 'query':
inputParams = ctx.state.query || ctx.request.query
break
case 'params':
inputParams = ctx.params
break
case 'body':
inputParams = ctx.state.body || ctx.request.body
break
case 'header':
inputParams = ctx.headers
}
const {
error,
value
} = Joi.validate(inputParams, schema, Object.assign({
abortEarly: true,
convert: true,
allowUnknown: true,
skipFunctions: false,
stripUnknown: part === 'body' ? true : false,
presence: 'optional',
noDefaults: false,
escapeHtml: false
}, options))
if (error) {
console.error(`schema validate ${part} error ${error}, ${part}`, inputParams)
return ctx.throws(new BadRequestError())
} else {
ctx.state[part] = value
}
}
return next()
}
}