$ npm i -g @nestjs/cli
nest new project-name
이후 폴더 이동 후 깃 설정
git remote add origin https://github.com/damin0320/hi-nest
main에 가니 APPmodule -> module에 가니 controller -> controller에 가니 Service????
아, 대충 이런 구조로 나오는구나?
그럼 싹 지우고(서비스와 컨트롤러) 모듈만 남기고 시작하면 어떻게 될까??
nest g co
이후 이름짓기
import { Controller, Get } from '@nestjs/common';
@Controller('movies')
export class MoviesController {
@Get()
getAll(){
return 'This will return all movies';
}
}
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"
}
}
"무언가 필요하다면 우리가 요청해야한다."
@Get("/:id")
getOne(@Param('id') id: string){
return `This will return one movie with the id : ${id}`;
}
@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}`};
잊지 말아야 할 것
"무언가 필요하다면 우리가 요청해야한다."
쿼리로 바로 하려면?
@Get("search")
search(@Query("year") searchingYear: string){
return `We are searching for a movie made after: ${searchingYear}`;
}
export class Movie{
id : number;
title:string;
year: number;
genres:string[];
}
이후 컨트롤러, 서비스 구현(get, post, delete ; 앞으로 코드는 깃허브, 플로우만 짜기)
post로 id 값이 늘어나는 것 확인했고 GET으로 가져와지는 것 확인(By postman)
주소에 이상한 것이 들어왔을 때 예외처리하기
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);
}
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에서 해결할 수 있는 방법이 있다.
이건 내일...