Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
Controllers should handle HTTP requests and delegate more complex tasks to providers. Providers are plain JavaScript classes with an @Injectable() decorator preceding their class declaration.
그러니까, provider는 contoroller가 처리하는 로직 중 좀 더 복잡한 업무를 따로 분할한 거라고 볼 수 있습니다.
예를 들어 특정한 데이터 핸들링이나 모델 학습 같은 경우 말이죠.
따라서 provider는 없어도 controller만으로도 굴러가긴 합니다. 다만 코드의 가독성이 떨어지겠죠.
nest cli를 활용해서 movies라는 이름을 가진 service를 만들어 보았다.
nest g s movies
movies 폴더가 생성되고 movies.service.ts가 생긴다.
service를 다음과 같이 정의합니다.
import { Injectable } 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 {
return this.movies.find(movie => movie.id === parseInt(id));
}
deleteOne(id: string): boolean {
this.movies.filter(movie => movie.id !== parseInt(id));
return true;
}
create(movieData) {
this.movies.push({ id: this.movies.length + 1, ...movieData });
}
}
이 service를 controller에 연결합니다.
해당 서비스를 constructor에 해정한 후 해당 함수들을 controller 단에서 사용하면 됩니다.
당연히 넘겨 받는 파라미터의 타입이 일치해야겠죠? url에서 추출하는 파라미터들은 전부 string으로 넘어오는 것에 유의 합시다.
import { Body, Controller, Delete, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { Movie } from './entities/movie.entity';
import { MoviesService } from './movies.service';
@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) {
this.moviesService.deleteOne(movieId);
}
@Patch('/:id')
patch(@Param('id') movieId: string, @Body() updateData) {
return {
updatedMovie: movieId,
...updateData,
};
}
}
'Node, Nest, Deno > 🦁 Nest.js' 카테고리의 다른 글
dotenv 대신 @nestjs/config을 사용해야하는 이유 + 활용 (0) | 2020.11.21 |
---|---|
DTO를 통한 검증을 위한 Pipe (Class Validator + mapped-types ...) (0) | 2020.11.19 |
Module에 대한 이해와 간단한 DI (0) | 2020.09.25 |
Controller, @Param, @Body, @Query ... (0) | 2020.09.24 |
Nest 프레임워크 소개 + 당근마켓이 소개하는 Nest의 이점 (0) | 2020.09.24 |