@opengis/fastify-table
Version:
core-plugins
82 lines (70 loc) • 3.36 kB
JavaScript
import config from '../../../../config.js';
const emailReg = /(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/g;
function checkField(key, val, options, idx, body) {
const type = options?.type?.toLowerCase?.();
const isrequired = options?.validators?.includes?.('required');
// validators: [required]
if (type === 'switcher') {
// skip nulls at non-required switchers, restrict invalid values
if (val && typeof val !== 'boolean') {
return {
error: 'not a boolean', key, idx,
};
}
// restrict nulls at required switchers
if (isrequired && typeof val !== 'boolean') {
return {
error: 'empty required', key, idx,
};
}
}
else if (isrequired && !val) {
if (options?.conditions) {
const allowed = JSON.parse(options?.conditions?.[2] || null);
const check = options?.conditions?.[1] === 'in' && Array.isArray(allowed)
? allowed.includes(body[options?.conditions?.[0] || ''])
: body[options?.conditions?.[0] || ''] === allowed;
if (!check) {
if (config.trace) console.log('validateData', 'skip conditions', key, body[options?.conditions?.[0] || ''], allowed);
return { key, val, idx };
}
}
return {
error: 'empty required', key, idx,
};
}
// validators: [email] / type: Email
if ((options.type?.toLowerCase() === 'email' || options?.validators?.includes('email')) && val && !val.match(emailReg)) {
return {
error: 'invalid email', key, val, idx,
};
}
return { key, val, idx };
}
function checkBody({ body = {}, arr = [], idx }) {
const res = Object.keys(body).reduce((acc1, key) => {
const input = arr.find(el => el.key === key) || {};
if (input.colModel?.length && input.type?.toLowerCase() === 'datatable') {
const result = body[key]?.reduce?.((acc, item, i) => {
const check = checkBody({ body: item, arr: input.colModel, idx: i });
acc.push(check);
return acc;
}, []);
acc1 = acc1.concat(result);
return acc1;
}
const check = checkField(key, body[key], input, idx, body) || {};
acc1.push({ key, val: body[key], ...check });
return acc1;
}, []);
const invalidField = res.find(el => el?.error);
if (invalidField) {
console.warn('invalid field: ', invalidField?.key, invalidField?.error);
return invalidField;
}
return { message: 'ok' };
}
export default function validateData({ body = {}, schema = {} }) {
const res = checkBody({ body, arr: Object.keys(schema).map(key => ({ ...schema[key], key })) });
return res;
}