UNPKG

validator-is

Version:

**validator-is: Simplify Your Validation and Swagger Documentation**

30 lines (29 loc) 874 B
import { applyDecorators } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger'; import { IsArray, IsBoolean, IsNotEmpty, IsNumber, IsNumberString, IsOptional, IsString, } from 'class-validator'; export function Is(type, required, description) { return applyDecorators(required ? IsNotEmpty() : IsOptional(), getValidatorByType(type), ApiProperty({ description, required, })); } function getValidatorByType(type) { if (type === 'number') { return IsNumber(); } else if (type === 'string') { return IsString(); } else if (type === 'boolean') { return IsBoolean(); } else if (type === 'numberString') { return IsNumberString(); } else if (type === 'array') { return IsArray(); } else { throw new Error(`Type ${type} is not supported`); } }