strapi/packages/core/utils/lib/validators.js
cyril lopez 65d612f364
V4/database ctb (#10589)
* Update yarn.lock

Signed-off-by: soupette <cyril.lpz@gmail.com>

* Remove useless options

Signed-off-by: soupette <cyril.lpz@gmail.com>

* Disable advanced options for components

Signed-off-by: soupette <cyril.lpz@gmail.com>

* Remove options from relations schema

Signed-off-by: soupette <cyril.lpz@gmail.com>

* Adapt ctb to new relation spec

Signed-off-by: soupette <cyril.lpz@gmail.com>

* Fix DataManagerProvider tests

Signed-off-by: soupette <cyril.lpz@gmail.com>

* Fix backend

Signed-off-by: soupette <cyril.lpz@gmail.com>
2021-07-07 17:29:57 +02:00

59 lines
1.4 KiB
JavaScript

'use strict';
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);
}
yup.addMethod(yup.mixed, 'notNil', isNotNill);
yup.addMethod(yup.mixed, 'notNull', isNotNull);
class StrapiIDSchema extends MixedSchemaType {
constructor() {
super({ type: 'strapiID' });
}
_typeCheck(value) {
return typeof value === 'string' || (Number.isInteger(value) && value >= 0);
}
}
yup.strapiID = () => new StrapiIDSchema();
/**
* Returns a formatted error for http responses
* @param {Object} validationError - a Yup ValidationError
*/
const formatYupErrors = validationError => {
console.log(validationError);
if (!validationError.inner) {
throw new Error('invalid.input');
}
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;
}, {});
};
module.exports = {
yup,
formatYupErrors,
};