2020-01-06 16:01:42 +01:00
|
|
|
import * as yup from 'yup';
|
2020-01-10 15:30:34 +01:00
|
|
|
import { translatedErrors } from 'strapi-helper-plugin';
|
2020-01-07 16:00:11 +01:00
|
|
|
|
2020-01-10 15:17:36 +01:00
|
|
|
const createYupSchema = form =>
|
|
|
|
yup.object().shape(
|
2020-01-07 16:00:11 +01:00
|
|
|
Object.keys(form).reduce((acc, current) => {
|
|
|
|
const { type, validations } = form[current];
|
|
|
|
acc[current] = createYupSchemaEntry(type, validations);
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, {})
|
|
|
|
);
|
|
|
|
|
|
|
|
const createYupSchemaEntry = (type, validations) => {
|
2020-01-06 16:01:42 +01:00
|
|
|
let schema = yup.mixed();
|
|
|
|
|
|
|
|
if (['text'].includes(type)) {
|
2020-01-07 16:00:11 +01:00
|
|
|
schema = yup.string(translatedErrors.string).nullable();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (['headers'].includes(type)) {
|
|
|
|
schema = yup
|
|
|
|
.array()
|
|
|
|
.of(
|
|
|
|
yup.object().shape({
|
|
|
|
key: yup.string().required(),
|
|
|
|
value: yup.string().required(),
|
|
|
|
})
|
|
|
|
)
|
|
|
|
.nullable();
|
|
|
|
}
|
2020-01-10 15:17:36 +01:00
|
|
|
|
2020-01-07 16:00:11 +01:00
|
|
|
if (['events'].includes(type)) {
|
|
|
|
schema = yup.array();
|
2020-01-06 16:01:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
Object.keys(validations).forEach(validation => {
|
|
|
|
const validationValue = validations[validation];
|
|
|
|
|
|
|
|
switch (validation) {
|
|
|
|
case 'required':
|
|
|
|
schema = schema.required(translatedErrors.required);
|
|
|
|
break;
|
|
|
|
case 'regex':
|
|
|
|
schema = schema.matches(validationValue, translatedErrors.regex);
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return schema;
|
|
|
|
};
|
|
|
|
|
2020-01-10 15:17:36 +01:00
|
|
|
export default createYupSchema;
|