Menu

Showing posts with label typescript. Show all posts
Showing posts with label typescript. Show all posts

Thursday, January 21, 2021

[NodeJS - NestJS] ข้อควรระวัง: Class transformer ไม่ตัด properties ส่วนเกินออกจาก Object ปลายทาง
[NodeJS - NestJS] Caution: Class transformer not stripping additional properties

Class transformer เป็นส่วนประกอบนึงของ NestJS ที่ใช้ในการแปลง JSON object ใดๆเป็น class instance ที่เราต้องการ และยังถูกใช้ในการแปลง request ที่ส่งเข้ามาให้เป็น class ที่เราต้องการโดยอัตโนมัติอีกด้วย

สมมติว่า เรามี function ใน controller ดังนี้
@Post()
async createRole (@Body() req: CreateRoleReqDto): Promise <Role> {
    let role = await this.roleService.createRole(req);
    return role;
}
และ class CreateRoleReqDto สำหรับ request ของเราเป็นดังนี้
export class CreateRoleReqDto{
    name: string;
    description?: string;
    permissionIds?: number[];
}
เมื่อเราส่ง request body ดังนี้
{
    "name":"test3",
    "description":"def",    
    "permissionIds": [1,2]
}
request body ของเราจะถูกแปลงเป็น instance ของ CreateRoleReqDto โดยอัตโนมัติ