Skip to content

Instantly share code, notes, and snippets.

@ivanzigoni
Last active November 10, 2024 13:32
Show Gist options
  • Save ivanzigoni/09017b874c62d97f3573cda2a074124b to your computer and use it in GitHub Desktop.
Save ivanzigoni/09017b874c62d97f3573cda2a074124b to your computer and use it in GitHub Desktop.
nestjs class validator decorators and configs for when we don't necessarily want to skip validation if value is null. (create and update)
import {
Controller,
Post,
Body,
ValidationPipe,
applyDecorators,
Patch,
UsePipes,
Param,
ParseIntPipe,
} from "@nestjs/common";
import { ApiProperty } from "@nestjs/swagger";
import { IsInt, IsNotEmpty, IsString, ValidateIf } from "class-validator";
import { PartialType } from "@nestjs/mapped-types";
function MayBeUndefined() {
return applyDecorators(
ValidateIf((_, value) => typeof value !== "undefined"),
);
}
class CreateUserDto {
@ApiProperty({
type: String,
required: true,
nullable: false,
})
@IsNotEmpty()
@IsString()
name: string;
@ApiProperty({
type: Number,
required: false,
nullable: false,
})
@MayBeUndefined()
@IsInt()
age?: number;
}
class UpdateUserDto extends PartialType(CreateUserDto, {
skipNullProperties: false,
}) {}
@UsePipes(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
}),
)
@Controller("users")
export class UsersController {
constructor() {}
@Post()
async createUser(
@Body() body: CreateUserDto,
) {}
@Patch(":id")
async updateUser(
@Param("id", ParseIntPipe) id: number,
@Body() body: UpdateUserDto,
) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment