@apizr-io/class-utils
Version:
Package containing all class-validator function with all custom apizr class validation functions
63 lines • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isOneOfTypes = void 0;
const class_transformer_1 = require("class-transformer");
const class_validator_1 = require("class-validator");
const validateObjectWithType = async (obj, type) => {
switch (type) {
case 'number':
case 'boolean':
case 'string':
case 'object':
return typeof obj === type && !Array.isArray(obj);
case 'null':
return obj === null;
case 'undefined':
return obj === undefined;
default: {
if ('type' in type) {
const types = Array.isArray(type.type) ? type.type : [type.type];
if (type.array && Array.isArray(obj)) {
const results = await Promise.all(obj.map((el) => (0, exports.isOneOfTypes)(types, el)));
return results.reduce((acc, result) => acc && result, true);
}
return (0, exports.isOneOfTypes)(types, obj);
}
if ('key' in type) {
if (typeof obj !== 'object' || !obj) {
return false;
}
if (type.array) {
if (!Array.isArray(obj)) {
return false;
}
const results = await Promise.all(obj.map((el) => (0, exports.isOneOfTypes)([{ key: type.key, value: type.value }], el)));
return results.reduce((acc, result) => acc && result, true);
}
const results = await Promise.all(Object.entries(obj).map(async ([key, value]) => {
const isKeyValid = await (0, exports.isOneOfTypes)([type.key], key);
return (isKeyValid &&
(0, exports.isOneOfTypes)(Array.isArray(type.value) ? type.value : [type.value], value));
}));
return results.reduce((acc, result) => acc && result, true);
}
if (!obj || Array.isArray(obj)) {
return false;
}
const instance = (0, class_transformer_1.plainToInstance)(type, obj);
const errors = await (0, class_validator_1.validate)(instance);
return errors.length === 0;
}
}
};
const isOneOfTypes = async (types, obj) => {
for (const type of types) {
const result = await validateObjectWithType(obj, type);
if (result === true) {
return true;
}
}
return false;
};
exports.isOneOfTypes = isOneOfTypes;
//# sourceMappingURL=object.utils.js.map