NestJS with NomadCoder

커피 내리는 그냥 사람·2021년 4월 13일
0

기업협업 인턴십

목록 보기
3/16

1. Basic

1. 설치 및 프로젝트 만들기

  • 공식문서 참고

    $ npm i -g @nestjs/cli
    nest new project-name

이후 폴더 이동 후 깃 설정

git remote add origin https://github.com/damin0320/hi-nest

2. 구조

1. 대략적으로?

main에 가니 APPmodule -> module에 가니 controller -> controller에 가니 Service????

아, 대충 이런 구조로 나오는구나?

2. 구조 & 아키텍처

  • module : 장고의 앱 개념, appmodule은 루트 모듈
  • controller는 단순히 URL을 가져와 함수에 매핑, 라우터 개념
  • service는 실제로 함수를 가지고 있는 부분, 비즈니스 로직을 실행하는 역할. 필요한 데이터베이스에 연락.

그럼 싹 지우고(서비스와 컨트롤러) 모듈만 남기고 시작하면 어떻게 될까??

2. REST API(영화 API 만들기)

1. controller 생성 : url

  1. 기본기 + 요청
nest g co
이후 이름짓기
  • movie.cont~
import { Controller, Get } from '@nestjs/common';

@Controller('movies')
export class MoviesController {


    @Get()
    getAll(){
        return 'This will return all movies';
    }
}
  • app.module~
import { Module } from '@nestjs/common';
import {MoviesController} from './movies/movies.controller'


@Module({
  imports: [],
  controllers: [MoviesController],
  providers: [],
})
export class AppModule {}
  • 결과

  • movies 부분이 라우터가 된다.

  • url을 id로 통제한다면?

    @Get("/:id")
    getOne(){
        return "This will return one movie"
    }
}

"무언가 필요하다면 우리가 요청해야한다."

  • example(param 요청)
    @Get("/:id")
    getOne(@Param('id') id: string){
        return `This will return one movie with the id : ${id}`;
    }
  1. post decorator(CRUD)
    @Post()
    create(){
        return "This will create a movie"
    }

    @Delete("/:id")
    remove(@Param('id') movieId:string){
        return `This will delete a movie with the id  : ${movieId}`};

2. more routes(데코레이터)

잊지 말아야 할 것

"무언가 필요하다면 우리가 요청해야한다."

  • 필요한 파라미터를 요청해야한다.
  1. 바디를 가져오려면 어떻게 해야 해?(Post)

  1. update, delete, patch..
  • 제이슨을 리턴했다!
  1. search에서 리퀘스트 받기 : 쿼리파라미터

쿼리로 바로 하려면?


    @Get("search")
    search(@Query("year") searchingYear: string){
        return `We are searching for a movie made after: ${searchingYear}`;
    }

3. service : 로직 관리

  1. 만들기
  • nest g s-> 이름
  1. entities폴더 무비 안에 넣고 movie.entity.ts만들기
  • 내용 :
export class Movie{
    id : number;
    title:string;
    year: number;
    genres:string[];
}
  1. 이후 컨트롤러, 서비스 구현(get, post, delete ; 앞으로 코드는 깃허브, 플로우만 짜기)

    post로 id 값이 늘어나는 것 확인했고 GET으로 가져와지는 것 확인(By postman)

  2. 주소에 이상한 것이 들어왔을 때 예외처리하기

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

.....

    deleteOne(id:string) {
        this.getOne(id)
        this.movies.filter(movie=>movie.id !== +id);
    }
  1. 중간 완성
    (controller)
import { Controller, Get, Param, Post, Delete, Patch, Body, Query } from '@nestjs/common';
import {MoviesService} from './movies.service'
import {Movie} from './entities/movie.entity'

@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.deleteOne(movieId);}

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



}

(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{
        const movie =  this.movies.find(movie=>movie.id=== +id);
        if(!movie){
            throw new NotFoundException(`Moive wiht ID : ${id} NOT FOUND`);
        }
        return movie;
    }

    deleteOne(id:string) {
        this.getOne(id)
        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});
    }
}
  • 맹점 : 해킹 등 유효성 검사에서 걸릴 수 있다.

  • 하지만 네스트JS에서 해결할 수 있는 방법이 있다.

이건 내일...

profile
커피 내리고 향 맡는거 좋아해요. 이것 저것 공부합니다.

0개의 댓글