@crowdin/app-project-module
Version:
Module that generates for you all common endpoints for serving standalone Crowdin App
61 lines (60 loc) • 2.38 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAutomationData = void 0;
const ajv_1 = __importDefault(require("ajv"));
const ajv = new ajv_1.default({ allErrors: true, strict: false, coerceTypes: true });
function formatAjvErrors(errors = []) {
if (!errors.length) {
return undefined;
}
return errors.reduce((acc, err) => {
const path = err.instancePath || '/';
acc[path] = err.message || '';
return acc;
}, {});
}
function removeEmptyValues(obj, options = { preserveEmptyArrays: true }) {
const { preserveEmptyArrays = true } = options;
if (Array.isArray(obj)) {
return obj
.map((item) => removeEmptyValues(item, options))
.filter((v) => v !== undefined &&
v !== null &&
!(Array.isArray(v) && v.length === 0 && !preserveEmptyArrays) &&
!(typeof v === 'object' && Object.keys(v).length === 0));
}
if (typeof obj === 'object' && obj !== null) {
const newObj = {};
for (const [key, value] of Object.entries(obj)) {
if (value === undefined) {
continue;
}
const cleanedValue = removeEmptyValues(value, options);
if (cleanedValue !== '' &&
cleanedValue !== null &&
cleanedValue !== undefined &&
!(Array.isArray(cleanedValue) && cleanedValue.length === 0 && !preserveEmptyArrays) &&
!(typeof cleanedValue === 'object' &&
!Array.isArray(cleanedValue) &&
Object.keys(cleanedValue).length === 0)) {
newObj[key] = cleanedValue;
}
}
return newObj;
}
return obj;
}
function validateAutomationData({ data, schema, preserveEmptyArrays = false, }) {
const cleaned = removeEmptyValues(data, { preserveEmptyArrays });
const validate = ajv.compile(schema);
const valid = validate(cleaned);
return {
valid: Boolean(valid),
errors: formatAjvErrors((validate === null || validate === void 0 ? void 0 : validate.errors) || []),
data: cleaned,
};
}
exports.validateAutomationData = validateAutomationData;