2019-06-24 15:31:22 +02:00
|
|
|
'use strict';
|
|
|
|
|
2019-12-24 14:49:44 +01:00
|
|
|
const yup = require('yup');
|
2020-02-14 11:42:03 +01:00
|
|
|
const _ = require('lodash');
|
|
|
|
|
2020-02-18 09:02:48 +01:00
|
|
|
const isNotNilTest = value => !_.isNil(value);
|
2020-02-17 14:51:21 +01:00
|
|
|
|
2020-02-18 09:02:48 +01:00
|
|
|
function isNotNill(msg = '${path} must be defined.') {
|
|
|
|
return this.test('defined', msg, isNotNilTest);
|
2020-02-17 12:04:17 +01:00
|
|
|
}
|
|
|
|
|
2020-02-18 09:02:48 +01:00
|
|
|
const isNotNullTest = value => !_.isNull(value);
|
|
|
|
function isNotNull(msg = '${path} cannot be null.') {
|
|
|
|
return this.test('defined', msg, isNotNullTest);
|
|
|
|
}
|
|
|
|
|
2020-05-28 13:02:06 +02:00
|
|
|
function arrayRequiredAllowEmpty(message) {
|
|
|
|
return this.test('field is required', message || '', value => _.isArray(value));
|
|
|
|
}
|
|
|
|
|
2020-02-18 09:02:48 +01:00
|
|
|
yup.addMethod(yup.mixed, 'notNil', isNotNill);
|
|
|
|
yup.addMethod(yup.mixed, 'notNull', isNotNull);
|
2020-05-28 13:02:06 +02:00
|
|
|
yup.addMethod(yup.array, 'requiredAllowEmpty', arrayRequiredAllowEmpty);
|
2019-11-04 14:47:58 +01:00
|
|
|
|
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-11-04 14:47:58 +01:00
|
|
|
}
|
|
|
|
|
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,
|
|
|
|
};
|