34 lines
806 B
JavaScript
Raw Normal View History

2019-06-24 15:31:22 +02:00
'use strict';
2019-12-24 14:49:44 +01:00
const yup = require('yup');
const _ = require('lodash');
yup.addMethod(yup.mixed, 'defined', function(msg = '${path} must be defined') {
return this.test('defined', msg, value => !_.isNil(value));
});
2019-06-24 15:31:22 +02:00
/**
* Returns a formatted error for http responses
* @param {Object} validationError - a Yup ValidationError
*/
const formatYupErrors = validationError => {
2019-12-24 14:57:58 +01:00
if (!validationError.inner) {
throw new Error('invalid.input');
}
2019-06-24 15:31:22 +02:00
if (validationError.inner.length === 0) {
if (validationError.path === undefined) return validationError.errors;
return { [validationError.path]: validationError.errors };
}
return validationError.inner.reduce((acc, err) => {
acc[err.path] = err.errors;
return acc;
}, {});
};
2019-12-24 14:49:44 +01:00
module.exports = {
yup,
formatYupErrors,
};