๐ ๊ฐ์ ํ๊ธฐ ๋ฐ ๋ฐฐ์ด์
- NEST.JS๋ Node.js ์ ํ๋ ์์ํฌ๋ก express ์์ ๋์๊ฐ ์ ์๋ค
- ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ, ํจ์ํ ํ๋ก๊ทธ๋๋ฐ, ํจ์ ๋ฐ์ํ ํ๋ก๊ทธ๋๋ฐ์ ์์๋ ์ผ๋ถ๋ถ ์ฌ์ฉ ๊ฐ๋ฅํ๋ฉฐ ์ํคํ
์ณ์ ๊ตฌ์กฐ๋ฅผ ์ ๊ณตํด์ค๋ค.
- Insomnia๋ฅผ ์ด์ฉํ์ฌ API ํ
์คํธ๋ฅผ ํด๋ณด์๋ค.
- ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ด์ฉํ์์ผ๋ฉฐ ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ํตํด ํด๋์ค์ ํจ์ ๊ธฐ๋ฅ์ ์ถ๊ฐํด์ค ์ ์์ ex)
@Get()
: get ๋ฆฌํ์คํธ๋ฅผ ํ ์ ์์
- ๋น์ฆ๋์ค ๋ก์ง์ ๊ด๋ฆฌํ๋ ์๋น์ค์ url ๋ผ์ฐํฐ ๊ธฐ๋ฅ์ ํ๋ ์ปจํธ๋กค๋ฌ๊ฐ ์๋ค
- Single-responsibility principle : ํ๋์ ๋ชจ๋, ํด๋์ค ํน์ ํจ์์ ํ๋์ ๊ธฐ๋ฅ์ ๊ผญ ์ฑ
์์ ธ์ผ ํจ
- DTO ๋ฐ์ดํฐ ์ ์ก ๊ฐ์ฒด : ์ฝ๋๋ฅผ ๊ฐ๊ฒฐํ๊ฒ ๋ง๋ค๊ณ ์ฟผ๋ฆฌ์ ๋ํ ์ ํจ์ฑ ๊ฒ์ฌ๊ฐ ๊ฐ๋ฅํ๊ฒ ํ๋ค
- ์๋น์ค์ ์ปจํธ๋กค๋ฌ ๊ฐ๋
์ด ์กฐ๊ธ ๋ ํ๋ฆฝ๋ ์์
์ด์๋ ๊ฑฐ ๊ฐ๋ค.
โ๏ธ ์ฝ๋
import {
Controller,
Get,
Param,
Post,
Delete,
Patch,
Body,
Query,
} from '@nestjs/common';
import { MoviesService } from './movies.service';
import { Movie } from './entities/movie.entity';
import { CreateMovieDto } from './dto/create-movie.dto';
import { UpdateMovieDto } from './dto/update-movie.dto';
@Controller('movies')
export class MoviesController {
constructor(private readonly moviesService: MoviesService) { }
@Get()
getAll(): Movie[] {
return this.moviesService.getAll();
}
@Get(":id")
getOne(@Param('id') movieId: number): Movie {
return this.moviesService.getOne(movieId);
}
@Post()
create(@Body() movieData: CreateMovieDto) {
return this.moviesService.create(movieData);
}
@Delete(":id")
remove(@Param('id') movieId: number) {
return this.moviesService.deleteOne(movieId);
}
@Patch(':id')
patch(@Param('id') movieId: number, @Body() updateData: UpdateMovieDto) {
return this.moviesService.update(movieId, updateData);
}
}
import { Injectable, NotFoundException } from '@nestjs/common';
import { Movie } from './entities/movie.entity';
import { CreateMovieDto } from './dto/create-movie.dto';
import { UpdateMovieDto } from './dto/update-movie.dto';
@Injectable()
export class MoviesService {
private movies: Movie[] = [];
getAll(): Movie[] {
return this.movies;
}
getOne(id: number): Movie {
const movie = this.movies.find(movie => movie.id === id);
if (!movie) {
throw new NotFoundException(`Movie with ID ${id} not found.`);
}
return movie;
}
deleteOne(id: number) {
this.getOne(id);
this.movies = this.movies.filter(movie => movie.id !== id);
}
create(movieData: CreateMovieDto) {
this.movies.push({
id: this.movies.length + 1,
...movieData,
});
}
update(id: number, updateData: UpdateMovieDto) {
const movie = this.getOne(id);
this.deleteOne(id);
this.movies.push({ ...movie, ...updateData });
}
}
export class Movie {
id: number;
title: string;
year: number;
genres: string[];
}