코드 작성 중 entity에 제한된 값을 가지는 컬럼을 만들기 위해 enum(열거형) 타입을 사용해보았다.
진행중인 프로젝트에서 유저가 특정 게시물에 적절하지 않은 내용이 있을 경우 신고를 할 수 있는 기능이 있다.
그래서 유저가 해당 게시물에 신고 요청을 하면 관리자가 내용을 확인하고 승인 또는 반려를 하게된다.
위의 로직에서 특정 신고에 3가지의 제한된 상태가 필요하다.
- 유저가 특정 게시물 신고를 완료한 상태 => AWAIT (관리자의 처리를 대기하는 상태)
- 관리자가 내용을 확인하고 신고를 승인한 상태 => ACCEPT
- 신고 내용이 적절하지 않아 반려한 상태 => REJECT
notification-status.enum.ts
먼저 enum 파일을 생성하여 상태 값을 정의해주었다.
export enum NotificationStatus {
AWAIT = 'AWAIT',
ACCEPT = 'ACCEPT',
REJECT = 'REJECT',
}
notification-status-validation.pipe.ts
요청받은 데이터를 체크하기 위해 validation-pipe를 만들어주었다.
transform 함수는 request body로 받는 status 데이터를 대문자로 바꿔서 enum에 설정해 놓은
status 값이 맞는지 확인하고 올바른 값이 아니면 에러를 뱉는다.
import { HttpException, PipeTransform } from "@nestjs/common";
import { NotificationStatus } from '../notification-status.enum'
export class NotificationStatusValidationPipe implements PipeTransform {
readonly StatusOptions = [
NotificationStatus.AWAIT,
NotificationStatus.ACCEPT,
NotificationStatus.REJECT
]
transform(value: any){
value = value.toUpperCase();
if(!this.isStatusValid(value)) {
throw new HttpException(`${value} 올바른 옵션이 아닙니다.`, 401)
}
return value;
}
private isStatusValid(status: any) {
const index = this.StatusOptions.indexOf(status);
return index !== -1
}
}
notification.controller.ts
관리자가 신고를 승인하는 api에 NotificationStatusValidationpipe를 적용해주었다.
@body 데코레이터를 사용해서 status 값을 받아 NotificationStatusValidationpipe을 통해 적절한 값인지
체크를 하고 service 계층으로 넘긴다.
// 신고 접수(어드민 계정만)
@Patch(':notiId/accept')
async acceptNotification(
@Param('notiId', ParseIntPipe) notiId: number,
@GetCurrentUser() user,
@Body('status', NotificationStatusValidationPipe) status: NotificationStatus
): Promise<any> {
const auth = user.auth;
return await this.notificationsService.acceptNotification(auth, notiId, status);
};
nestJS와 TypeScript를 처음 접할때만 해도 앞이 깜깜했는데 점점 적응하고 있는 것 같다.
'Development > TIL' 카테고리의 다른 글
데이터 형상 관리 (특정 버전으로 롤백) (0) | 2023.06.10 |
---|---|
증분식 데이터 형상관리 : Increment Data Versioning (0) | 2023.06.03 |
git stash(생성, 삭제, 복구) (0) | 2023.06.01 |
TypeORM Isolation Level (0) | 2023.05.30 |
Typeorm Transaction (0) | 2023.05.29 |