본문 바로가기

개발/JavaScript

[NestJS] Controller, Service

 

generate

- generate 커맨드 라인으로 NestJS의 요소 생성

- movies controller 생성

nest generate|g co
? movies

자동으로 module에 import

 

 

Movies Controller

- url 매핑, 리퀘스트를 받고 Query, Body를 넘기는 역할

- 데코레이터: url 매핑, 파라미터 예) @Get, @Param...

- 상단에 사용하는 데코레이터 import

import {
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Patch,
  Body,
  Query,
} from '@nestjs/common';

@Controller('movies') //controller 단위 url 설정
export class MoviesController {
  constructor(private readonly moviesService: MoviesService) {}
  
  @Get() // decorator
  getAll() {
    return this.moviesService.getAll();
  }

  @Get('search') // id에 걸리지 않게 위에 작성
  search(@Query('year') searchingYear: string) { // @Query: url get 방식으로 파라미터 받기
    return `We are searching for a movie made after: ${searchingYear}: `;
  }


  @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') //put: 모든 리소스 업데이트, patch: 리소스의 일부분만 업데이트
  patth(@Param('id') movieId: string, @Body() updateData) {
    return this.moviesService.update(movieId, updateData);
  }
}

* put: 모든 리소스 업데이트, patch: 리소스의 일부분만 업데이트

 

 

Single-responsibility principle

- 하나의 module, class 혹은 function이 하나의 기능은 꼭 책임져야 한다

 

Movies Service

- 비즈니스 로직 수행

- Movies Service 생성

nest g s
? movies

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

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

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

  getOne(id: string): Movie {
    const movie = this.movies.find((movie) => movie.id === +id); // +id == parseInt(id)
    if (!movie) {
      // 잘못된 요청 예외 처리
      throw new NotFoundException(`Movie with ID: ${id} not found`);
    }
    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);
    this.deleteOne(id);
    this.movies.push({ ...movie, ...updateData });
  }
}

 

Entity 생성

- movie.entity.ts

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

 

 

post,get '/movies'
예외처리

 

 

'개발 > JavaScript' 카테고리의 다른 글

[NestJS] Modules, DI  (0) 2022.08.10
[NestJS] DTO, 유효성 검사 Validation  (0) 2022.08.10
[NestJS] Project setup, 구조  (0) 2022.08.10
[JS] Promise, async, await  (0) 2022.08.09
[JS] call, apply, bind 함수  (0) 2022.08.09