@apizr-io/class-utils
Version:
Package containing all class-validator function with all custom apizr class validation functions
56 lines • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.IsRecord = 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 areKeysValid = (keys, type) => {
const keysResults = keys.map((key) => {
if (type === 'string') {
return typeof key === 'string';
}
return !isNaN(Number(key));
});
return keysResults.reduce((acc, result) => acc && result, true);
};
const getErrorMessage = (propertyName, keyType, types, each) => {
const recordValueType = (0, types_utils_1.getTypesName)(types);
const singleRecordType = `Record<${keyType}, ${recordValueType}>`;
return `Object ${propertyName} is not compliant to type ${singleRecordType}${each ? '[]' : ''}`;
};
function IsRecord(allowedRecordType, validationOptions) {
return (object, propertyName) => {
const types = Array.isArray(allowedRecordType)
? allowedRecordType
: [allowedRecordType];
const keyType = (validationOptions === null || validationOptions === void 0 ? void 0 : validationOptions.key) || 'string';
(0, class_validator_1.registerDecorator)({
name: 'isRecord',
target: object.constructor,
propertyName,
constraints: [],
options: {
message: () => getErrorMessage(propertyName, keyType, types, validationOptions === null || validationOptions === void 0 ? void 0 : validationOptions.each),
...validationOptions,
},
validator: {
async validate(value) {
if (!value) {
return false;
}
const objectKeys = Object.keys(value);
if (!areKeysValid(objectKeys, keyType)) {
return false;
}
const valuesToCheck = (validationOptions === null || validationOptions === void 0 ? void 0 : validationOptions.each) && Array.isArray(value)
? value.flatMap((obj) => Object.values(obj))
: Object.values(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.IsRecord = IsRecord;
//# sourceMappingURL=is-record.decorator.js.map