I’ve created a controller that receives a POST/ ...
request.
one of the parameters is optional and it’s for example called contentType
.
in the service i check if the contentType is equal to something and regarding to the result it does something.
because the parameter is not mandatory, I want to set it a default value.
in that case I used @Transform()
decorator in the DTO.
When I do the call I don’t see the default values I defined in the decorator it in the service.
Expected:
sort = {date: -1}
contentType = ‘json’
Result in Service:
sort = undefined
contentType = undefined
My NestJS Config:
Using nestJS V10
reflect-metadata version: ^0.2.2″
- Main.ts:
const app = await NestFactory.create(AppModule);
...
app.useGlobalPipes(
new ValidationPipe({
transform: true,
transformOptions: { enableImplicitConversion: true },
whitelist: true,
}),
);
- DTO:
export class ListDto {
... more...
@IsObject()
@IsOptional()
@Transform(({ value }) => value ?? { date: -1 })
sort?: Record<string, SortOrder>; // Types Defined above I just don't want to pollute the example.
@IsString()
@IsOptional()
@IsIn(['json', 'xlsx', 'csv'], {
message: 'contentType must be one of: json, xlsx, csv',
})
@Transform(({ value }) => value ?? 'json')
contentType?: Extension;
}
- Controller:
@Post('list')
async list(@Body() list: ListDto): Promise<any> {
try {
console.log(list.sort) // <-- Expected default value defined in decorator, but undefined
console.log(list.contentType) // <-- Expected default value defined in decorator, but undefined
return await this.someService.list(list);
} catch (error) {
....
}
}
- request body:
{
"param1" : "Some value",
"param2" : "Some other"
//NOT Passing sort or contentType
}
- Service method declaration:
async list({
...more...
sort,
contentType,
}: ListeDto): Promise<List> {
console.log(contentType) <-- Expect to see the default value from the decorator, but undefined
console.log(sort) <-- Expect to see the default value from the decorator, but undefined
...some implementation...
}
Where did I do wrong?
Or what am I missing?