nestjs_nomad_04.project_movies service

ohbin Kwon·2021년 9월 26일
0
  1. service 모듈 만들기
import { Injectable } from '@nestjs/common';
import { Movie } from './entities/movie.entity';

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

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

    // 인자는 string으로 받지만, Movie의 id는 number이기 때문에 변환이 필요함
    getOne(id:string):Movie{
        return this.movies.find(movie => movie.id === parseInt(id)) // parseInt(id) = +id
    }

    remove(id:string):boolean {
        this.movies.filter(movie => movie.id !== +id)
        return true
    }

    create(movieData){
        this.movies.push({
            id: this.movies.length + 1,
            ...movieData,
        })
    }
}
  • fake database를 이용
  • 인터페이스 설정
export class Movie {
    id: number
    title: string
    year: number
    genres: string[]
}
  1. controller에 적용
import { Controller,Delete,Get, Param, Post, Patch, Body, Query } from '@nestjs/common';
import { Movie } from './entities/movie.entity';
import { MoviesService } from './movies.service';

@Controller('movies')
export class MoviesController {

        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){
        return this.moviesService.create(movieData)
    }

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

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


}

  1. 예외처리
import { Injectable, NotFoundException } from '@nestjs/common';
import { Movie } from './entities/movie.entity';

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

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

    // 인자는 string으로 받지만, Movie의 id는 number이기 때문에 변환이 필요함
    getOne(id:string):Movie{
        const movie = this.movies.find(movie => movie.id === parseInt(id)) // parseInt(id) = +id
        if(!movie) {
            throw new NotFoundException(`Movie with ID ${id} not found. `)// nestjs에서 제공하는 예외처리 기능
        }
        return movie
    }

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

    create(movieData){
        this.movies.push({
            id: this.movies.length + 1,
            ...movieData,
        })
    }

    update(id: string, updateData){
        const movie = this.getOne(id)
        this.remove(id)
        this.movies.push({ ...movie, ...updateData})
    }
}
  1. 유효성 검사
profile
개발 로그

0개의 댓글