objectypes
Version:
A type-safe library to transform and validate objects
47 lines (46 loc) • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateObject = void 0;
const ramda_1 = require("ramda");
const type_validator_1 = require("./type-validator");
const property_1 = require("./metadata/property");
function validateObject(klass, obj) {
const presenceErrors = [];
const typeErrors = [];
const properties = (0, property_1.findClassPropertiesMetadata)(klass);
if (properties) {
properties.forEach(property => {
const { name, propertyKey, nullable, type, target } = property;
const jsonPropertyName = name !== null && name !== void 0 ? name : propertyKey;
const value = (0, ramda_1.path)(jsonPropertyName.split('.'), obj);
// Property presence validation
if (value === undefined && !nullable) {
// eslint-disable-next-line max-len
presenceErrors.push(jsonPropertyName);
}
// Nested object property validation
if (type && !nullable) {
const validateNestedObject = (val) => {
const { presenceErrors, typeErrors } = validateObject(type, val);
presenceErrors.push(...presenceErrors);
typeErrors.push(...typeErrors);
};
if (Array.isArray(value)) {
value.forEach(validateNestedObject);
}
else {
validateNestedObject(value);
}
}
// Property primitive type validation
if (!type && value !== undefined) {
const typeError = (0, type_validator_1.isTypeValid)(target, propertyKey, value);
if (typeError) {
typeErrors.push(typeError);
}
}
});
}
return { presenceErrors, typeErrors };
}
exports.validateObject = validateObject;