UNPKG

@apizr-io/class-utils

Version:

Package containing all class-validator function with all custom apizr class validation functions

45 lines 1.64 kB
"use strict"; 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; 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 (!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