티스토리 뷰

Node.js

Nest.js Core

세이브 2021. 12. 29. 18:09

 

Controller / Handler / Service / Repository 정리

 

 

Controller 란? 
컨트롤러는 들어오는 요청을 처리하고 클라이언트에 응답을 반환합니다. 
컨트롤러는 @Controller 데코레이터로 클래스를 데코레이션하여 정의됩니다.

@Controller('/boards')
export class BoardsController{

}

데코레이터는 인자로  Controller 에 의해서 처리하는 경로를 받습니다. 

@Controller('boards')
export class BoardsController {
    constructor(private boardsService: BoardsService){}

    @Get()
    getAllBoard(): Board[]{
        return this.boardsService.getAllBoards()
    }

    @Post()
    @UsePipes(ValidationPipe)   //  handler-level pipe
    createBoard(
        @Body() CreateBoardDto : CreateBoardDto
    ): Board {

        return this.boardsService.createBoard(CreateBoardDto);
    }

    // localhost:5000?id=askdjflan&pwd=askdfnk
    @Get('/:id')
    getBoardById(@Param('id') id: string){
        return this.boardsService.getBoardById(id);
    }

    @Delete('/:id')
    deleteBoard(@Param('id') id : string) : void{
        this.boardsService.deleteBoard(id);
    }

    @Patch('/:id/status')
    updateBoardStatus(
        @Param('id') id: string,
        @Body('status', BoardStatusValidationPipe) status: BoardStatus
    ){
        return this.boardsService.updateBaordStatus(id, status)
    }


}



 

 


Handler 란? 
핸들러는 @Get, @Post, @Delete 등과 같은 데코레이터로 장식된 컨트롤러 클래스 내의 단순한 메서드입니다.

@Controller('/boards')
export class BoardsController{
    @Get()
    getBoards(): string{
        return 'This action returns all boards';
    }
}

 

 

 

 


Service 란 ? 
서비스는 소프트웨어 개발 내의 공통 개념이며, Nest.js , javascript에서만 쓰이는 개념이 아니다
@Injectable 데코레이터로 감싸져서 모듈에 제공되며, 이 서비스 인스턴스는 애플리케이션 전체에서 
사용될 수 있다.

서비스는 컨트롤러에서 데이터의 유효성 체크를 하거나 데이터베이스에 아이템을 생성하는 등의
작업을 한다.

 

@Injectable()
export class BoardsService {

    // constructor(
    //     @InjectRepository(BoardRepository)
    //     private baordREpository: BoardRepository,
    // ){}



    private boards: Board[] = [];

    
    getAllBoards(): Board[]{
        return this.boards;
    }
 
   
    createBoard(createBoardDto: CreateBoardDto){
        // const title = createBoardDto.title;

        const { title, description } = createBoardDto;
        const board: Board = {
            id: randomUUID(),  
            title: title,
            description: description,
            status: BoardStatus.PUBLIC
        }
        this.boards.push(board);
        return board;
    } 


    getBoardById(id: string): Board{
        const found = this.boards.find((board) => board.id === id);
        
        if(!found){
            throw new NotFoundException(`Can't find Board with id ${id}`);
        }
        return found;
    }

    deleteBoard(id: string) : void{
        const found = this.getBoardById(id);
        this.boards = this.boards.filter((board) => board.id !== found.id);
    }

    updateBaordStatus(id: string, status: BoardStatus): Board{
        const board = this.getBoardById(id);
        board.status = status;
        return board;
    }
}

 

 

 



Repository 란 무엇인가? 
리포지토리는 엔티티 개체와 함께 작동하며 엔티티 찾기, 삽입, 업데이트, 삭제 등을
처리합니다.


데이터베이스와 관련된 일은 서비스에서 하는게 아닌 Repository에서 해준다
이것을 Repository pattern 이라고도 부른다 


        Request
User -----------------> Controller 
        Response            |
                            |
                            |
                        Service
                            |
                            |
                            |
                        Repository


데이터베이스와 관련된 일은 서비스에서 하는게 아닌 Repository에서 해준다
이것을 Repository pattern 이라고도 부른다 


'Node.js' 카테고리의 다른 글

DI (Dependecy Injection)  (0) 2021.12.29
Providers  (0) 2021.12.29
Express 미들웨어  (0) 2021.09.03
Express  (0) 2021.09.03
Node.js HTTP  (0) 2021.09.03
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
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
글 보관함