250x250
Notice
Recent Posts
Recent Comments
관리 메뉴

탁월함은 어떻게 나오는가?

[Swagger] Swagger Request Body 표시해주기 위해 @ApiBody 작성 방법 본문

[Snow-ball]프로그래밍(컴퓨터)/여러가지

[Swagger] Swagger Request Body 표시해주기 위해 @ApiBody 작성 방법

Snow-ball 2023. 7. 27. 21:45
반응형

parameter로 배열을 받을 경우에 dto에서 타입을 @ApiProperty로 타입을 지정해줘도 안되는 배열안의 값이 null 로 표시가 되는 현상이 발생하였다.

 

기억을 위해서 예시를 작성하고 겪었던 문제 상황과 해결 방법을 메모해보겠다.

 

 

 


 

 

 

1. 배열이 존재하고 안의 타입이 null 로 발생하였다.

 

 

 


 

 

 

2. dto안에 @ApiProperty를 선언해주고 type: 안에 배열을 선언해주고 그 안에 타입을 선언해주면 표시가 된다는 글이 존재해서 따라서 진행해봤지만 실패했다. 다만, null > {} 로 변경이 되었다.

 

적용한 일부분의 코드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
abstract class ItemClass implements Item {
  itemId: string;
  name: string;
  expireDay: number;
  price: number;
  count: number;
}
 
@IsArray()
@Type(() => ItemClass)
@ApiProperty({
   type: [ItemClass],
})
public items!: Item[];
cs

 

위의 코드를 보면 ItemsClass를 사용한 이유는 Item이 iterface로 만들어서 값으로 만들수 없다고 에러가 발생하여서 구현체로 만들어 주었다. 

ERROR 내용: TS2693: 'Item' only refers to a type, but is being used as a value here.

 

그리고 나서 결과는 밑에 사진과 같다.

 

 

 

 


 

 

 

3. 세번째로 했던 방법은 @ApiBody를 사용하는 방법이다. 밑에 코드를 참고하자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@ApiBearerAuth('access_token')
@Patch('/')
@ApiResponse({ status: 200, description: `${TWO_HUNDRED_OK}` })
@ApiResponse({ status: 500, description: `${INTERNAL_SERVER_ERROR}` })
@ApiBody({
  type: 'application/x-www-form-urlencoded',
  required: true,
  schema: {
    type: 'object',
    properties: {
      items: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            itemId: {
              type: 'string',
            },
            name: {
              type: 'string',
            },
            expireDay: {
              type: 'number',
            },
            price: {
              type: 'number',
            },
            count: {
              type: 'number',
            },
          },
        },
      },
    },
  },
})
private async users(
  @Body() dto: UsersInputDto,
): Promise<UsersOutputDto> {
 
  return await this.service.users(dto);
}
cs

 

 

결과론적으로 원하는 방법이였다. 밑에 사진에서 그 결과를 확인할 수 있다.

 

 

 

 

 

반응형
Comments