decoval
Version:
DecoVal is a decorator-driven validation pattern that allows you to add validation rules directly to the properties of TypeScript classes, simplifying data control and increasing code readability and reusability.
22 lines (21 loc) • 1.15 kB
JavaScript
import { ValidationError } from "./error/validation.error";
import { registerValidation } from "./register.validation";
export function DvEnum(options) {
const { values, in: inOption } = options;
const enumValues = Array.isArray(values)
? values
: Object.values(values).filter((v) => typeof v !== "number" || !Object.values(values).includes(v.toString()));
const inMessage = (inOption === null || inOption === void 0 ? void 0 : inOption.message) || `The field must be one of the following values: ${enumValues.join(", ")}.`;
return function (target, propertyKey) {
const alreadyApplied = Reflect.getMetadata("valenum:applied", target, propertyKey);
if (alreadyApplied) {
throw new Error(`The @ValEnum decorator has already been applied to the field "${propertyKey}"`);
}
Reflect.defineMetadata("valenum:applied", true, target, propertyKey);
registerValidation(target, propertyKey, (value) => {
if (!enumValues.includes(value)) {
throw new ValidationError(inMessage.replace("{property}", propertyKey));
}
});
};
}