결과 화면

 


https://docs.nestjs.com/recipes/crud-generator

NestJS CRUD 생성기에 대한 자세한 설명은 위의 NestJs 공식 문서를 참고한다.

 

1. nest g resource folder-name

folder-name 부분에 원하는 폴더명을 작성하면 된다.

nest g resource folder-name 명령어는 NestJs의 컨트롤러, 모듈, 서비스, dto, 엔티티 등 NestJs 개발에 필요한 여러 리소스 파일들을 설치해 준다. = CRUD 생성기

 

옵션 선택이 나온다면 REST API로 선택하고, yes를 입력한다.

 

게시판을 만들기 위해서 nest g resource board 명령어를 실행해 board 폴더를 만들었다.

 

2. board.controller.ts

컨트롤러(controller)는 들어오는 요청을 처리하고 클라이언트에 응답을 반환하는 역할을 한다.

라우팅 메커니즘은 어떤 컨트롤러가 어떤 요청을 받는지 제어한다.

 

CRUD 생성기를 사용하면 @Post, @Get, @Patch, @Delete 메서드가 기본적으로 만들어진다.

import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { BoardService } from './board.service';
import { CreateBoardDto } from './dto/create-board.dto';
import { UpdateBoardDto } from './dto/update-board.dto';

@Controller('board')
export class BoardController {
  constructor(private readonly boardService: BoardService) {}

  @Post()
  create(@Body() createBoardDto: CreateBoardDto) {
    return this.boardService.create(createBoardDto);
  }

  @Get()
  findAll() {
    return this.boardService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.boardService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateBoardDto: UpdateBoardDto) {
    return this.boardService.update(+id, updateBoardDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.boardService.remove(+id);
  }
}

 

3. board.service.ts

컨트롤러에 들어가는 서비스(service)이다.

CRUD 생성기를 사용하면 create, find, update, remove 메서드가 기본적으로 만들어진다.

import { Injectable } from '@nestjs/common';
import { CreateBoardDto } from './dto/create-board.dto';
import { UpdateBoardDto } from './dto/update-board.dto';

@Injectable()
export class BoardService {
  create(createBoardDto: CreateBoardDto) {
    return 'This action adds a new board';
  }

  findAll() {
    return `This action returns all board`;
  }

  findOne(id: number) {
    return `This action returns a #${id} board`;
  }

  update(id: number, updateBoardDto: UpdateBoardDto) {
    return `This action updates a #${id} board`;
  }

  remove(id: number) {
    return `This action removes a #${id} board`;
  }
}

+ Recent posts