Add validation rule of repeatable component to mongo connector

This commit is contained in:
Alexandre Bodin 2019-11-15 12:20:52 +01:00
parent 3e8816161a
commit bd188d2bfb

View File

@ -406,7 +406,7 @@ const buildSearchOr = (model, query) => {
}, []); }, []);
}; };
function validateRepeatableInput(value, { key, min, max }) { function validateRepeatableInput(value, { key, min, max, required }) {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {
const err = new Error(`Component ${key} is repetable. Expected an array`); const err = new Error(`Component ${key} is repetable. Expected an array`);
err.status = 400; err.status = 400;
@ -416,20 +416,24 @@ function validateRepeatableInput(value, { key, min, max }) {
value.forEach(val => { value.forEach(val => {
if (typeof val !== 'object' || Array.isArray(val) || val === null) { if (typeof val !== 'object' || Array.isArray(val) || val === null) {
const err = new Error( const err = new Error(
`Component ${key} as invalid items. Expected each items to be objects` `Component ${key} has invalid items. Expected each items to be objects`
); );
err.status = 400; err.status = 400;
throw err; throw err;
} }
}); });
if (min && value.length < min) { if (
(required === true || (required !== true && value.length > 0)) &&
(min && value.length < min)
) {
const err = new Error( const err = new Error(
`Component ${key} must contain at least ${min} items` `Component ${key} must contain at least ${min} items`
); );
err.status = 400; err.status = 400;
throw err; throw err;
} }
if (max && value.length > max) { if (max && value.length > max) {
const err = new Error(`Component ${key} must contain at most ${max} items`); const err = new Error(`Component ${key} must contain at most ${max} items`);
err.status = 400; err.status = 400;