All files / middlewares validate.js

100% Statements 16/16
100% Branches 2/2
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 224x 4x 4x 4x   48x 71x 71x 71x       71x 25x 25x   46x 46x     4x  
const Joi = require('joi');
const { status: httpStatus } = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
 
const validate = (schema) => (req, res, next) => {
  const validSchema = pick(schema, ['params', 'query', 'body']);
  const object = pick(req, Object.keys(validSchema));
  const { value, error } = Joi.compile(validSchema)
    .prefs({ errors: { label: 'key' }, abortEarly: false })
    .validate(object);
 
  if (error) {
    const errorMessage = error.details.map((details) => details.message).join(', ');
    return next(new ApiError(httpStatus.BAD_REQUEST, errorMessage));
  }
  Object.assign(req, value);
  return next();
};
 
module.exports = validate;