strapi/packages/core/utils/lib/validators.js

63 lines
1.5 KiB
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');
const MixedSchemaType = yup.mixed;
const isNotNilTest = value => !_.isNil(value);
function isNotNill(msg = '${path} must be defined.') {
return this.test('defined', msg, isNotNilTest);
}
const isNotNullTest = value => !_.isNull(value);
function isNotNull(msg = '${path} cannot be null.') {
return this.test('defined', msg, isNotNullTest);
}
function arrayRequiredAllowEmpty(message = '${path} is required') {
return this.test('field is required', message, value => _.isArray(value));
}
yup.addMethod(yup.mixed, 'notNil', isNotNill);
yup.addMethod(yup.mixed, 'notNull', isNotNull);
yup.addMethod(yup.array, 'requiredAllowEmpty', arrayRequiredAllowEmpty);
class StrapiIDSchema extends MixedSchemaType {
constructor() {
super({ type: 'strapiID' });
}
_typeCheck(value) {
2020-06-04 14:27:16 +02:00
return typeof value === 'string' || (Number.isInteger(value) && value >= 0);
}
}
yup.strapiID = () => new StrapiIDSchema();
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,
};