UNPKG

nestjs-custom-class-validators

Version:

This package contains a few custom validator I have found to be repetitive, So I made templates that handles both class-validator checks and Swagger configuration

42 lines 2.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.swaggerProp = exports.isArrayFn = exports.isUUIDFn = exports.isNumberFn = exports.isBooleanFn = exports.isEnumFn = exports.isStringFn = exports.notEmptyFn = void 0; const swagger_1 = require("@nestjs/swagger"); const class_validator_1 = require("class-validator"); const each = true; const notEmptyFn = (customKeys, isArray) => (0, class_validator_1.IsNotEmpty)(Object.assign({ message: `${customKeys}: Must not be empty` }, (isArray && { each: true }))); exports.notEmptyFn = notEmptyFn; const isStringFn = (customKeys, isArray = false) => (0, class_validator_1.IsString)(Object.assign({ message: `${customKeys}: Must be a string` }, (isArray && { each }))); exports.isStringFn = isStringFn; const isEnumFn = (customKey, validEnum, isArray = false) => { const message = ` ${customKey}: Must be ${isArray ? "a list containing" : "either"} ${Object.values(validEnum).join(" or ")}`; return (0, class_validator_1.IsEnum)(validEnum, Object.assign({ message }, (isArray && { each: true }))); }; exports.isEnumFn = isEnumFn; const isBooleanFn = (customKeys) => (0, class_validator_1.IsBoolean)({ message: `${customKeys}: Must be true or false` }); exports.isBooleanFn = isBooleanFn; const isNumberFn = (customKeys, isArray) => (0, class_validator_1.IsNumber)({}, Object.assign({ message: `${customKeys}: Must be a ${isArray ? "number array" : "number"}` }, (isArray && { each }))); exports.isNumberFn = isNumberFn; const isUUIDFn = (customKey, isArray) => (0, class_validator_1.IsUUID)("all", Object.assign({ message: `${customKey}: Must be ${isArray ? "an array of valid UUIDs" : "a valid UUID"}` }, (isArray && { each }))); exports.isUUIDFn = isUUIDFn; const isArrayFn = (customKey) => (0, class_validator_1.IsArray)({ message: `${customKey}: Must be array` }); exports.isArrayFn = isArrayFn; const swaggerProp = (details) => { const { description, validEnum, optional, isArray, type, format } = details; let defaultValue = details.defaultValue; if (typeof defaultValue == "string") { defaultValue = defaultValue.trim(); } const types = { boolean: Boolean, string: String, number: Number, array: Array, media: "string", }; const options = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ description }, (format && { format })), (type && { type: types[type] })), (isArray && { isArray })), (validEnum && { enum: validEnum })), (defaultValue && { default: defaultValue })); return optional ? (0, swagger_1.ApiPropertyOptional)(options) : (0, swagger_1.ApiProperty)(options); }; exports.swaggerProp = swaggerProp; //# sourceMappingURL=commonDecoratorFunctions.js.map