UNPKG

@apizr-io/class-utils

Version:

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

38 lines 1.72 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IsUnion = void 0; const class_validator_1 = require("class-validator"); const object_utils_1 = require("./utils/object.utils"); const types_utils_1 = require("./utils/types.utils"); const getErrorMessage = (propertyName, types, each) => { const unionValueType = (0, types_utils_1.getTypesName)(types, each); return `Object ${propertyName} is not compliant to type ${unionValueType}`; }; function IsUnion(types, validationOptions) { return (object, propertyName) => { (0, class_validator_1.registerDecorator)({ name: 'isUnion', target: object.constructor, propertyName, constraints: [], options: { message: () => getErrorMessage(propertyName, types, validationOptions === null || validationOptions === void 0 ? void 0 : validationOptions.each), ...validationOptions, }, validator: { async validate(value) { if (!value) { return false; } const valuesToCheck = (validationOptions === null || validationOptions === void 0 ? void 0 : validationOptions.each) && Array.isArray(value) ? value.flatMap((obj) => obj) : [value]; const results = await Promise.all(valuesToCheck.map((obj) => (0, object_utils_1.isOneOfTypes)(types, obj))); return results.reduce((acc, el) => acc && el, true); }, }, }); }; } exports.IsUnion = IsUnion; //# sourceMappingURL=is-union.decorator.js.map