저번에 사용했던 그림으로, Service는 Repository에서 데이터를 받아와서 비즈니스 로직을 다루는 layer이다.
Repository Layer를 대충 만들기는 했지만, 그래도 사용은 되기 때문에 이 Repository를 바탕으로 Service를 만들어보자.
우선 nest의 convention에 따라 service를 생성한다.
service에서는 repository에서 데이터를 받아오기 때문에, service가 repository에게 의존하는 관계가 된다.
내부에서 repository를 사용해야 하기 때문에, 생성자를 통해서 repository를 만들어서 가져오자.
constructor(private readonly messagesRepository: MessagesRepository) {
this.messagesRepository = new MessagesRepository();
}
우선 이렇게 만들기는 했지만, 이후에는 절대 이렇게 사용하지 않는다.
messagesRepository를 직접 만들어서 사용하는 것이 아니라, DI를 통해 주입받도록 만들어야 한다.
constructor에서 messagesRepository를 생성하지 않는 것이 목표다.
일단 이렇게 만들고 service layer의 개발에 집중해보자.
service에서 만들 메서드는 다음과 같다.
export class MessagesService {
constructor(private readonly messagesRepository: MessagesRepository) {
this.messagesRepository = new MessagesRepository();
}
async findOne(id: string){}
async findAll(id: string){}
async create(id: string){}
}
내부 코드는 작성하지 않았지만, 이런 의문이 들 수도 있다.
어차피 이거 repository에 있는 내용이랑 똑같은데, 굳이 service를 만들어야 해?
하지만 스프링에서도 같은 구조를 사용했었고, 그렇기에 왜 이렇게 사용하는지는 알 수 있을 것이다.
Service Layer에서는 이런 repository의 메서드들 조합해 비즈니스 로직을 만들고, 이런 부분에 대해 공통 관심사인 트랜잭션 처리등의 역할을 하기 때문에 service Layer는 굉장히 중요하다.
export class MessagesService {
constructor(private readonly messagesRepository: MessagesRepository) {
this.messagesRepository = new MessagesRepository();
}
async findOne(id: string){
return this.messagesRepository.findOne(id);
}
async findAll(id: string){
return this.messagesRepository.findAll();
}
async create(content: string){
return this.messagesRepository.create(content);
}
}
결국 repository layer의 메서드들을 그대로 사용하는 코드들이지만, 그래도 만들어보도록 하자.
그리고 controller에 연결 한 후, http 요청을 보내보자.
controller에 작성한 코드는 간단하기에 생략하겠다.
이렇게 POST 요청을 보내니
messages.json 파일에 이렇게 생성이 되고
GET으로 해당 데이터를 가져올 수 있었다.
마지막으로 여기에 예외의 경우를 추가해보자.
당연히 없는 경우의 id로 조회할 수 있다.
이렇게 해당 데이터가 없는 경우에도 404 에러가 아닌, 정상적인 200 코드를 넘기고 있는 것을 볼 수 있다.
이런 경우에 NotFoundException을 사용해 예외를 추가해보자.
@Get('/:id')
async getMessage(@Param('id') id: string){
const message = await this.messagesService.findOne(id)
if(!message){
throw new NotFoundException('Message not found');
}
return message
}
이렇게 Null인 경우에 NotFoundException을 throw하면 nest에서 해당 예외에 맞는 에러코드로 변경해준다.
이렇게 해당 경우에 맞는 에러를 반환해주는 것을 볼 수 있다.
이번 글에서는 생성자에서 해당 의존성 클래스들을 생성해서 사용했었다.
다음 글에서는 이 부분을 바꿔보도록 하겠다.
'Node > Nest' 카테고리의 다른 글
Nest에서 멀티 모듈 생성하는 방법 (1) | 2025.07.06 |
---|---|
Nest에서의 IOC/DI 알아보기 (0) | 2025.07.06 |
Nest에서 파일 시스템을 통해 repository layer 구현하기 (0) | 2025.07.05 |
Nest에서 파이프를 통해 요청 DTO 검사하기 (1) | 2025.07.04 |
Nest 모듈과 컨트롤러 만들어보기 (0) | 2025.07.03 |