NestJS optional Body Fields

How can i accept a partial object as Body using NestJS
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';

export class UpdateUserDto {
@ApiProperty({ required: false, nullable: true })
@IsString()
@IsOptional()
public name: string | null;
@ApiProperty({ required: false, nullable: true })
@IsString()
@IsOptional()
public email: string | null;
@ApiProperty({ required: false, nullable: true })
@IsString()
@IsOptional()
public password: string | null;
}
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';

export class UpdateUserDto {
@ApiProperty({ required: false, nullable: true })
@IsString()
@IsOptional()
public name: string | null;
@ApiProperty({ required: false, nullable: true })
@IsString()
@IsOptional()
public email: string | null;
@ApiProperty({ required: false, nullable: true })
@IsString()
@IsOptional()
public password: string | null;
}
@Patch()
@UseGuards(AuthGuard)
@ApiOkResponse({ description: 'Updated User', type: User })
@ApiNotFoundResponse({ description: 'No User with this id' })
update(@Req() request, @Body() updateUserDto: UpdateUserDto) {
console.log(updateUserDto);
//return this.userService.updateById(request['user'].id, updateUserDto);
}
@Patch()
@UseGuards(AuthGuard)
@ApiOkResponse({ description: 'Updated User', type: User })
@ApiNotFoundResponse({ description: 'No User with this id' })
update(@Req() request, @Body() updateUserDto: UpdateUserDto) {
console.log(updateUserDto);
//return this.userService.updateById(request['user'].id, updateUserDto);
}
when i send the request body {"name":"test","email":"test"} it prints UpdateUserDto {}, but i expect UpdateUserDto {name: "test", email: "test", password: null} what am i doing wrong ??
1 Reply
Bored Student
Bored StudentOP3w ago
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './CreateUserDto';

export class UpdateUserDto extends PartialType(CreateUserDto) {}
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './CreateUserDto';

export class UpdateUserDto extends PartialType(CreateUserDto) {}
I found this option, but it doesn't work either.

Did you find this page helpful?