언어/Nest.js

Service & Entity

MellowHoney 2024. 4. 1. 18:34
728x90
반응형

Service

기능

클래스, 변수, 함수 기능 구현

생성

$ nest g s [이름]

구조

  • 기본 구조
  • spec파일은 test파일이므로 지워도 무방
  • app.module.ts에 자동 생성
  • movie.setvice.ts
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 {
    const movie = this.movies.find((movie) => movie.id === +id);
    if (!movie) {
      throw new NotFoundException(`Movie with ID ${id} not found.`); // nest 기본 제공 404 예외처리
    }
    return movie;
  }

  deleteOne(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); // id값인 movie를 가져온다.
    this.deleteOne(id); //모든 movie를 가져와 해당 movie를 지우고
    this.movies.push({ ...movie, ...updateData }); // create old + new
  }
}

Entity

기능

json형식 db저장소

생성

해당 모듈 폴더에 Entities - entity.ts파일 생성

구조

  • json db
  • movies.entity.ts
export class Movie {
  id: number;
  title: string;
  year: number;
  genres: string[];
}
반응형