@wenn/onb
Version:
onb-core
66 lines (57 loc) • 2.08 kB
JavaScript
import { getPageSchema, getCodeSchema } from './schemas';
let Validator = require('jsonschema').Validator;
let v = new Validator();
const { REACT_APP_ENV } = process.env;
const devEnviroment = REACT_APP_ENV === 'dev' || REACT_APP_ENV === 'stage' || window.log === 'true';
const isEmpty = (obj = {}) => Object.keys(obj).length === 0;
export const validateSendSchema = (page, data, fields) => {
if (page && data && fields) {
let currentSchema = getPageSchema(page, fields);
if (devEnviroment) {
console.log('send :: page ::', page);
console.log('send :: fields ::', fields[page]);
}
if (!isEmpty(currentSchema)) {
v.addSchema(currentSchema, page);
let sendValidation = v.validate(data, currentSchema);
if (devEnviroment) console.log('send :: validation ::', sendValidation);
if (!sendValidation.valid) {
sendValidationAlert(true, page, sendValidation.errors);
}
}
}
};
export const validateEndSchema = (code, data, fields) => {
if (code && data && fields) {
let currentSchema = getCodeSchema(code, fields);
if (devEnviroment) {
console.log('end :: code ::', code);
console.log('end :: fields ::', fields[code]);
}
if (!isEmpty(currentSchema)) {
v.addSchema(currentSchema, code);
let endValidation = v.validate(data, currentSchema);
if (devEnviroment) console.log('end :: validation ::', endValidation);
if (!endValidation.valid) {
sendValidationAlert(false, code, endValidation.errors);
}
}
}
};
const sendValidationAlert = (isSend, where, errors) => {
const identifier = isSend ? 'Send / Page' : 'Get / Code';
let errorsStr = `${errors.map(err => `\n${err.stack}`)}`;
if (devEnviroment) console.log(`${identifier} schema errors :: `, errorsStr);
const messageText = `
We have a validation alert!
${identifier}: ${where}.
Errors: \t${errorsStr}.
`;
if (sendlog) {
sendlog('error', {
error_type: 'invalidSchema',
schema_type: identifier,
error_desc: messageText
});
}
};