티스토리 뷰

개발/Nestjs

[nestjs] todo 만들기

Lovizu 2021. 5. 12. 23:21

NESTJS  만들기 프로젝트 1

TODO

 

프로젝트 생성 ( 아래 명령으로 nest project 생성)

nest new todo

 

todo 리소스 생성 ( resource 명령을 사용하면 entity, controller, module, dto가 생성된다)

nest g res todo

or 

nest generate resource todo

 

filter + validate 모듈 설치 

npm i --save class-validator class-transformer

 

filter + validate 적용

// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(   // <-- 여기 추가
    new ValidationPipe({
      transform: true,
    }),
  );
  await app.listen(3000);
}
bootstrap();

 

Todo Entity

// todo.entity.ts
export enum Status {
  READY = 'ready',
  DONE = 'done',
}

export class Todo {
  id?: number;
  content: string;
  status: Status;
}

 

DTO

// create-todo.dto.ts
import { Status } from '../entities/todo.entity';
import { IsNotEmpty, Length, IsEnum } from 'class-validator';

export class CreateTodoDto {
  @IsNotEmpty({ message: '내용은 필수 값입니다.' })
  @Length(2, 50)
  readonly content: string;

  @IsEnum(Status, { message: '잘못된 상태 값 입니다.' })
  readonly status: Status = Status.READY;
}

 

service

//todo.service.ts
import { Todo } from './entities/todo.entity';
import { Injectable } from '@nestjs/common';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';
import { NotFoundException } from '@nestjs/common';

@Injectable()
export class TodoService {
  private id = 0;
  private todos: Todo[] = [];

  create(createTodoDto: CreateTodoDto): Todo {
    this.id++;
    const todo = {
      id: this.id,
      ...createTodoDto,
    };

    this.todos.push(todo);
    return todo;
  }

  findAll(): Todo[] {
    return this.todos;
  }

  findOne(id: number): Todo {
    const findId = this.todos.findIndex((todo) => todo.id === id);
    if (findId === -1) {
      throw new NotFoundException();
    }
    return this.todos[findId];
  }

  update(id: number, updateTodoDto: UpdateTodoDto) {
    const findId = this.todos.findIndex((todo) => todo.id === id);
    if (findId === -1) {
      throw new NotFoundException();
    }

    this.todos[findId] = {
      ...this.todos[findId],
      ...updateTodoDto,
    };

    return this.todos[findId];
  }

  remove(id: number): void {
    this.todos = this.todos.filter((todo) => todo.id !== id);
  }
}

 

controller

// todo.controller.ts

import { Todo } from './entities/todo.entity';
import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import { TodoService } from './todo.service';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';
import { HttpCode } from '@nestjs/common';

@Controller('todo')
export class TodoController {
  constructor(private readonly todoService: TodoService) {}

  @Post()
  create(@Body() createTodoDto: CreateTodoDto): Todo {
    return this.todoService.create(createTodoDto);
  }

  @Get()
  findAll(): Todo[] {
    return this.todoService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: number): Todo {
    return this.todoService.findOne(id);
  }

  @Patch(':id')
  update(@Param('id') id: number, @Body() updateTodoDto: UpdateTodoDto): Todo {
    return this.todoService.update(id, updateTodoDto);
  }

  @Delete(':id')
  @HttpCode(204)
  remove(@Param('id') id: number): void {
    this.todoService.remove(id);
  }
}

 

 

계속 작성중...

 

 

github.com/yousung/nestjs-todo/commit/f6b29f475dcf9dc166d333c3ffc5a3183d94c21d

댓글


최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday