movies service 2

emily,h·2022년 7월 16일
0

movies.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 {
  constructor(private readonly moviesService: MoviesService) {}

  @Get()
  getAll(): Movie[] {
    // return `This will return all movies`;
    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.deleteOne(movieId);
  }

  @Patch('/:id')
  patch(@Param('id') movieId: string, @Body() updateData) {
    return this.moviesService.update(movieId, updateData);
  }
}

movies.service

import { Injectable, NotFoundException } 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 {
    if (!movie) {
      throw new NotFoundException(`Movie with ID ${id} not found.`);
    }
    return movie;
  }

  deleteOne(id: string) {
    this.getOne(id);
    // filter한 데이터를 다시 movie에 넣어줌
    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.deleteOne(id); // 해당 아이디 삭제
    // 과거의 데이터에 새로운 데이터를 더해서 새로운 movie를 만든다.
    this.movies.push({ ...movie, ...updateData });
  }
}

1개의 댓글

comment-user-thumbnail
2023년 3월 1일

It can be pretty useful, but I can say that I'm more interested in good music than movies. I think that a good soundtrack can make anything better, and I even have many playlists downloaded with Tubidy to listen to them on a daily basis. And in order to escape reality, music is a better way to get distracted, but I guess that some people may say that I'm wrong, there's no accounting for taste anyway.

답글 달기