Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] Interceptor를 활용해 서버 응답 포멧 통일 #141

Merged
merged 3 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion apps/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { TaskModule } from '@/task/task.module';
import { TypeormConfig } from '../config/typeorm.config';
import { AppService } from '@/app.service';
import { AppController } from '@/app.controller';
import { HttpLoggingInterceptor } from '@/common/httpLog.Interceptor';
import { ResponseInterceptor } from './common/interceptor/response.interceptor';
import { HttpLoggingInterceptor } from '@/common/interceptor/httpLog.Interceptor';
import { AllExceptionsFilter } from '@/common/allException.filter';
import { AccountModule } from '@/account/account.module';
import { ProjectModule } from '@/project/project.module';
Expand All @@ -34,6 +35,10 @@ import { PlanningPokerModule } from './planning-poker/planning-poker.module';
controllers: [AppController],
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: ResponseInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: HttpLoggingInterceptor,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const RESPONSE_MESSAGE = 'response_message';
export const ResponseMessage = (message: string) => SetMetadata(RESPONSE_MESSAGE, message);
4 changes: 4 additions & 0 deletions apps/server/src/common/decorator/response-status.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { SetMetadata } from '@nestjs/common';

export const RESPONSE_STATUS = 'response_status';
export const ResponseStatus = (status: number) => SetMetadata(RESPONSE_STATUS, status);
21 changes: 21 additions & 0 deletions apps/server/src/common/interceptor/response.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { BaseResponse } from '../BaseResponse';
import { RESPONSE_STATUS } from '../decorator/response-status.decorator';
import { RESPONSE_MESSAGE } from '../decorator/response-message.decorator';

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, BaseResponse> {
constructor(private readonly reflector: Reflector) {}

intercept(context: ExecutionContext, next: CallHandler): Observable<BaseResponse> {
const status = this.reflector.get<number>(RESPONSE_STATUS, context.getHandler()) || 200;
const message =
this.reflector.get<string>(RESPONSE_MESSAGE, context.getHandler()) ||
'요청이 성공적으로 처리되었습니다.';

return next.handle().pipe(map((data) => BaseResponse.create(status, message, data)));
}
}
44 changes: 18 additions & 26 deletions apps/server/src/project/controller/project.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Param,
Patch,
Post,
Res,
UseGuards,
} from '@nestjs/common';
import { ProjectService } from '@/project/service/project.service';
Expand All @@ -18,7 +19,7 @@ import { UpdateContributorRequest } from '@/project/dto/update-contributor-reque
import { TaskEvent } from '@/task/dto/task-event.dto';
import { TaskService } from '@/task/service/task.service';
import { EventType } from '@/task/domain/eventType.enum';
import { BaseResponse } from '@/common/BaseResponse';
import { ResponseMessage } from '@/common/decorator/response-message.decorator';

@UseGuards(AccessTokenGuard)
@Controller('project')
Expand All @@ -29,68 +30,59 @@ export class ProjectController {
) {}

@Get('invitations')
@ResponseMessage('프로젝트 멤버 초대 목록 조회에 성공했습니다.')
async getInvitations(@AuthUser() user: Account) {
return new BaseResponse(
200,
'프로젝트 멤버 초대 목록 조회에 성공했습니다.',
await this.projectService.getInvitations(user.id)
);
return await this.projectService.getInvitations(user.id);
}

@Get(':id')
@ResponseMessage('프로젝트 상세 조회에 성공했습니다.')
async getProject(@AuthUser() user: Account, @Param('id') projectId: number) {
return new BaseResponse(
200,
'프로젝트 상세 조회에 성공했습니다.',
await this.projectService.getProject(user.id, projectId)
);
return await this.projectService.getProject(user.id, projectId);
}

@Get(':id/members')
@ResponseMessage('프로젝트 멤버 목록 조회에 성공했습니다.')
async getMembers(@AuthUser() user: Account, @Param('id') projectId: number) {
return new BaseResponse(
200,
'프로젝트 멤버 목록 조회에 성공했습니다.',
await this.projectService.getContributors(user.id, projectId)
);
return await this.projectService.getContributors(user.id, projectId);
}

@Post()
@ResponseMessage('프로젝트 생성이 성공했습니다.')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡
생성은 201 Created 가 더 적절할 것 같습니다!

async create(@AuthUser() user: Account, @Body() body: CreateProjectRequest) {
return new BaseResponse(
200,
'프로젝트 생성이 성공했습니다.',
await this.projectService.create(user.id, body.title)
);
return await this.projectService.create(user.id, body.title);
}

@Post(':id/invite')
@ResponseMessage('프로젝트 멤버 초대가 성공했습니다.')
async invite(
@AuthUser() user: Account,
@Param('id') projectId: number,
@Body() body: InviteUserRequest
) {
await this.projectService.invite(user.id, projectId, body.username);
return new BaseResponse(200, '프로젝트 멤버 초대가 성공했습니다.', {
return {
message: 'Successfully invite user',
success: true,
});
};
}

@Patch(':id/invite')
@ResponseMessage('프로젝트 멤버 초대 처리가 성공했습니다.')
async updateInvitation(
@AuthUser() user: Account,
@Param('id') projectId: number,
@Body() body: UpdateContributorRequest
) {
await this.projectService.updateInvitation(user.id, projectId, body.contributorId, body.status);
return new BaseResponse(200, '프로젝트 멤버 초대 처리가 성공했습니다.', {
return {
message: 'Successfully update invitation',
success: true,
});
};
}

@Post(':id/update')
@ResponseMessage('이벤트 처리 완료했습니다.')
async handleEvent(
@AuthUser() user: Account,
@Param('id') projectId: number,
Expand All @@ -115,6 +107,6 @@ export class ProjectController {
default:
throw new BadRequestException('올바르지 않은 이벤트 타입입니다.');
}
return new BaseResponse(200, '이벤트 처리 완료했습니다.', response);
return response;
}
}
9 changes: 3 additions & 6 deletions apps/server/src/project/controller/projects.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,16 @@ import { ProjectService } from '@/project/service/project.service';
import { AccessTokenGuard } from '@/account/guard/accessToken.guard';
import { AuthUser } from '@/account/decorator/authUser.decorator';
import { Account } from '@/account/entity/account.entity';
import { BaseResponse } from '@/common/BaseResponse';
import { ResponseMessage } from '@/common/decorator/response-message.decorator';

@UseGuards(AccessTokenGuard)
@Controller('projects')
export class ProjectsController {
constructor(private projectService: ProjectService) {}

@Get()
@ResponseMessage('프로젝트 목록 조회에 성공했습니다.')
async getProjects(@AuthUser() user: Account) {
return new BaseResponse(
200,
'프로젝트 목록 조회에 성공했습니다.',
await this.projectService.getUserProjects(user.id)
);
return await this.projectService.getUserProjects(user.id);
}
}
16 changes: 5 additions & 11 deletions apps/server/src/task/controller/task.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,22 @@ import { TaskService } from '@/task/service/task.service';
import { AuthUser } from '@/account/decorator/authUser.decorator';
import { Account } from '@/account/entity/account.entity';
import { AccessTokenGuard } from '@/account/guard/accessToken.guard';
import { BaseResponse } from '@/common/BaseResponse';
import { ResponseMessage } from '@/common/decorator/response-message.decorator';

@UseGuards(AccessTokenGuard)
@Controller('task')
export class TaskController {
constructor(private taskService: TaskService) {}

@Get()
@ResponseMessage('태스크 목록이 정상적으로 조회되었습니다.')
async getAll(@AuthUser() user: Account, @Query('projectId') projectId: number) {
return new BaseResponse(
200,
'태스크 목록이 정상적으로 조회되었습니다.',
await this.taskService.getAll(user.id, projectId)
);
return await this.taskService.getAll(user.id, projectId);
}

@Get(':id')
@ResponseMessage('태스크가 정상적으로 조회되었습니다.')
async get(@AuthUser() user: Account, @Param('id') id: number) {
return new BaseResponse(
200,
'태스크가 정상적으로 조회되었습니다.',
await this.taskService.get(user.id, id)
);
return await this.taskService.get(user.id, id);
}
}
Loading