영화 Rest api 만들기

  1. url 가져오기 & function 실행 파일 만들기

    -> cli 기능 중 하나인 generator 사용

    • generator로 새로운 컨트롤러 생성할 것

    => nest g co(controller 생성)

    => movies(controller 이름)

-> controllers가 자동으로 변환됨 & movie파일 생성됨

  • app.module
import { Module } from '@nestjs/common';
import { MoviesController } from './movies/movies.controller';

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

api 라우터 만들기

  • movies.controller

    -> Get 추가

    import { Controller, Get } from '@nestjs/common';
      
    @Controller('movies') // url의 Entry Point 컨트롤
    export class MoviesController {
      
        @Get()
        getAll(){
            return "This will return all movies";
        }
    }
    

=> localhost:3000/movies로 들어가서 확인

​ ->새로운 Get 추가

import { Controller, Get } from '@nestjs/common';

@Controller('movies')
export class MoviesController {

    @Get()
    getAll(){
        return "This will return all movies";
    }

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

}

=> localhost:3000/movies/1

insomnia

  1. new request 생성

    -> 이름: Hi nest

    -> url 복붙

요청 방법

  1. parameter decorator

ex) getOne()에서 요청 -> parameter 요청

=> url에 있는 id라는 parameter를 get함

위에선 parameter의 decorator로 먼저 요청함

  • Get()안이랑 param()안이 같아야함!!!
import { Controller, Get, Param } from '@nestjs/common';

@Controller('movies')
export class MoviesController {

    @Get()
    getAll(){
        return "This will return all movies";
    }

    @Get("/:id")
    getOne(@Param("id") movieId: string){
        return `This will return one movie with the id: ${movieId}`
    }

}

image

  1. post decorator & Delete decorator

    import { Controller, Delete, Get, Param, Post } from '@nestjs/common';
       
    @Controller('movies')
    export class MoviesController {
       
        @Get()
        getAll(){
            return "This will return all movies";
        }
       
        @Get("/:id")
        getOne(@Param("id") movieId: string){
            return `This will return one movie with the id: ${movieId}`
        }
       
        @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}`;
        }
       
    }
       
    

image image

  1. Put

-> update하는 것

=>put은 모든 리소스 업데이트

따라서 patch 사용 -> 리소스의 일부분만 업데이트

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

@Controller('movies')
export class MoviesController {

    @Get()
    getAll(){
        return "This will return all movies";
    }

    @Get("/:id")
    getOne(@Param("id") movieId: string){
        return `This will return one movie with the id: ${movieId}`
    }

    @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}`;
    }

    @Patch(':/id')
    path(@Param('id') movieId: string){
        return `This will patch a movie with the id: ${movieId}`;
    }


}

decorator

  1. Query
  2. Body

decorator body 확인

  1. insomnia에서 Post에 body 추가

image

  1. Post
@Post()
    create(@Body() movieData){ //Body 받기
        console.log(movieData) //terminal
        return "This will create a movie";
    }

->terminal 에서 확인 가능

@Post()
    create(@Body() movieData){
        console.log(movieData)
        return movieData;
    }

-> movieData가 insomnia에 출력

  1. Patch
@Patch(':/id')
    path(@Param('id') movieId: string, @Body() updateData){
        return {
            updatedMovie: movieId,
            ...updateData,
        };
    }

-> 업데이트할 movie의 id & 보낼 데이터의 오브젝트 리턴(json도 리턴됨)

image **★직접 요청하지 않으면, 아무것도 제공X ->parameter 직접 요청 **

->search에서 리퀘스트 받도록

ex) 주소로 year 같은 query argument 보내기

image

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

    @Get("/:id")
    getOne(@Param("id") movieId: string){
        return `This will return one movie with the id: ${movieId}`
    }

=> search가 get보다 밑에 있으면 NestJS는 search를 id로 판단하므로 위에 적기!

image