View

TIL | NestJS_REST_API_Controller

Melody:) 2021. 10. 11. 14:00

NestJS REST API

이번 블로그 부터는 NestJS를 사용하여 영화 관련 API를 만들어보겠습니다.

오늘은 그 시작의 첫번째, Controller입니다.


1. controller 생성

nest cli를 사용하여, controller를 생성해보겠습니다.
아래와 같이 nest cli가 지원하는 명령어가 있으며,

nest generate controller 의 약자로 아래의 명령어를 실행해주고,

nest g co

'컨트롤러명' 을 적어줍니다.

놀라운 것은!!! movie 이름을 가진 폴더안에 컨트롤러가 자동 생성되고 동시에 module에 import가 자동으로 되었다!!!
Amazing!!!!!!!!

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


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

이때 movie폴더안에 생성된 spec파일은 테스트 파일이다.


2. movies.controller.ts 살펴보기

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

@Controller('movies') // 엔트리 포인트가 된다.
export class MoviesController {
    @Get()
    getAll() {
        return 'This will return all movies';
    }
}


3. url의 Path Parameter 받기

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

@Controller('movies')
export class MoviesController {
    @Get('/:id_1')
    getOne(@Param('id_1') id_2: string) { // url에 있는 prarmeter를 받아온다.
        return `This will return one movie with the id: ${id_2}`
    }

}


4. @Param 데코데이터 사용하여 CRUD 함수 만들기

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_1')
    getOne(@Param('id_1') id_2: string) { // url에 있는 prarmeter를 받아온다.
        return `This will return one movie with the id: ${id_2}`
    }

    @Post()
    create(){
        return `This will create a movie`;
    }

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

    // @Put() // 모든 리소스 업데이트

    @Patch('/:id') // 리소스의 일부분만 업데이트
    path(@Param('id') id:string) {
        return `This will patch a movie with the id : ${id}`;
    }
}

5. @Body

1) 업데이트할 영화 정보를 리턴하기

    @Patch('/:id')
    path(@Param('id') id:string, @Body() updateData) {
        return {
            updateMovie :id,
            updateData 
        };
    }
}


⭐️꿀팁 ⭐️

upadateData를 ...updateData로 표시하면 {}가 풀리면서, 합쳐진다.

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


2) 생성할 영화정보 리턴하기

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


6. @Query('') ''안에는 넘길 값의 변수명을 적어준다.

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

 


👍 완성된 movie.controller

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

@Controller('movies')
export class MoviesController {
    @Get()
    getAll() {
        return 'This will return all movies';
    }

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

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

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

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

}

'NestJS' 카테고리의 다른 글

TIL | NestJS_REST_API_Validation  (0) 2021.10.11
TIL | NestJS_REST_API_Service  (0) 2021.10.11
TIL | NestJS_REST_API_Settings  (0) 2021.10.11
TIL | TypeScript_기본문법2  (0) 2021.10.10
TIL | TypeScript_기본 문법1  (0) 2021.10.10
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31