View

TIL | NestJS_REST_API_Service

Melody:) 2021. 10. 11. 15:25

NestJS_REST_API_Service

우리는 Single-responsibility principle에 따라 코드를 작성할 예정이다.


Single-responsibility principle란?

하나의 module, class 혹은 fuction이 하나의 기능은 꼭 책임져야한다는 뜻이다.

1. Service 생성

nest g s

2. service에서 사용할 데이터베이스를 생성한다.

entity 폴더를 만들어 movie.entity.ts 파일을 생성하여 데이터의 모델을 지정해준다.

export class Movie {
    id: number;
    title:string;
    year:number;
    genres: string[];
}

3. movie.service.ts 작성

import { Injectable, Delete } from '@nestjs/common';
import { Movie } from './entities/movie.entity';

@Injectable()
export class MoviesService {
    private movies: Movie[] = [];

    getAll(): Movie[] {
        return this.movies;
    }

    getOne(id:string): Movie {
        // return this.movies.find(movie => movie.id === parseInt(id)); 아래와 같은 문장
        return this.movies.find(movie => movie.id === +id);
    }

    deleteOne(id:string) {
        this.getOne(id);
        this.movies = this.movies.filter(movie => movie.id !== +id);
    }

    createOne(movieData): boolean {
        this.movies.push({
            id: this.movies.length + 1,
            ...movieData
        })        
        return true; 
    }

}

4. movie.service.ts에서 작성한 함수들을 controller로 가져와 사용해준다.

import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query } from '@nestjs/common';
import { Movie } from './entities/movie.entity';
import { MoviesService } from './movies.service';

@Controller('movies')
export class MoviesController {

    ///service import하기
    constructor(private readonly moviesService: MoviesService) {}

    @Get()
    getAll(): Movie[] {
        return this.moviesService.getAll();
    }


    @Get(':id')
    getOne(@Param('id') movieId: string): Movie{
        return this.moviesService.getOne(movieId);
    }

    @Post()
    create(@Body() movieData){
        console.log(movieData);
        return this.moviesService.createOne(movieData);
    }

    @Delete(':id')
    remove(@Param('id') movieId:string){
        return this.moviesService.deleteOne(movieId);
    }

    @Patch(':id') 
    path(@Param('id') movieId:string, @Body() updateData) {
        return {
            updateMovie :movieId,
            ...updateData 
        };
    }

}

5. Error 예외처리

@Injectable()
export class MoviesService {
    private movies: Movie[] = [];

    getOne(id:string): Movie {
        const movie =  this.movies.find(movie => movie.id === +id);
        if (!movie) {
            throw new NotFoundException(`Movie with ID ${id} not found.`)
        } 
        return movie;
    }

존재하지 않는 영화의 아이디를 요청하였을 경우, 에러메시지를 띄도록 한다.

  • NotFoundException 사용

    {
    "statusCode": 404,
    "message": "Movie with ID 2 not found.",
    "error": "Not Found"
    }

주의 : update

가짜 데이터 베이스로 update를 구현해야하므로 기존 데이터에서 해당 id를 가진 데이터를 삭제하고,
새로업데이하는 데이터를 추가하는데, 이때,
{...movie, ...updateData}는 앞의 데이터에 뒤의 데이터를 덮어 씌우는 기능을 한다.

    update(id:string, updateData) {
        const movie = this.getOne(id);
        this.deleteOne(id);
        console.log(this.getAll())
        this.movies.push({...movie, ...updateData});
    }

[
  {
    "id": 1,
    "title": "기생충",
    "director": "봉준호",
    "year": "2019",
    "genre": "1"
  },
  {
    "id": 2,
    "title": "기생충",
    "director": "봉준호",
    "year": "2019",
    "genre": "스릴러"
  },
  {
    "id": 3,
    "title": "기생충",
    "director": "봉준호",
    "year": "2019",
    "genre": "스릴러"
  }
]

[
  {
    "id": 2,
    "title": "기생충",
    "director": "봉준호",
    "year": "2019",
    "genre": "스릴러"
  },
  {
    "id": 3,
    "title": "기생충",
    "director": "봉준호",
    "year": "2019",
    "genre": "스릴러"
  },
  {
    "id": 1,
    "title": "기생충",
    "director": "봉준호",
    "year": "2019",
    "genre": "1"
  }
]

'NestJS' 카테고리의 다른 글

TIL | NestJS_REST_API_Module  (0) 2021.10.11
TIL | NestJS_REST_API_Validation  (0) 2021.10.11
TIL | NestJS_REST_API_Controller  (0) 2021.10.11
TIL | NestJS_REST_API_Settings  (0) 2021.10.11
TIL | TypeScript_기본문법2  (0) 2021.10.10
Share Link
reply
«   2024/10   »
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