express 기반 -> express middleware 사용 가능
선택적으로 Fastify
사용 가능
기본적으로 typescript 지원, pure Javscript 도 사용 가능
구조를 가지고 있고, 순서와 룰도 있고
모듈 간의 의존성이 명확
TypeScript 로 구축
테스트 환경 제공, 확장성, 유지관리가 용이한 애플리케이션 아키텍쳐를 제공
npm i -g @nestjs/cli
nest new project-name
neststudy
라는 prject를 생성하니
이러한 프로젝트 구조가 만들어졌다.
app.controller.ts
: a basic controller with a single route
app.controller.spect.ts
: the unit tests for the controller
app.module.ts
: the root module of the application
app.service.ts
: A basic service with a single method
main.ts
: the entry file of the application which uses the core function NestFactory
to create a Nest application instance
자동으로 생성된 main.ts
NestFactory
는 application instance를 만들기 위한 class 이다.
create()
함수가 application instance를 return 한다.
main.ts에서는 HTTP listener를 작동시켰다.
request를 받고, response를 return 하는 것을 관리한다.
routing을 통해 어떤 controller가 어떤 request를 받을지 결정한다.
class와 decorator 를 이용할 거다. decorator는 class 와 metadata를 연결시키고, Nest가 routing map을 형성하게 만든다.
@Controller()
: basic controller를 정의하기 위해 필요한 decorator
연관된 route들을 그룹화하고, 중복 코드를 방지하는 기능을 한다.
$ nest g controller controller_name
명령어를 통해 controller 를 생성할 수 있다.
request handler가 JS object 나 array 를 return 하면 자동으로 JSON 으로 바꿔준다. 하지만 JS Primitive Type 을 return 할 경우에는 값만 전송하기 때문에 더 간단해진다. 또한 status code 를 자동으로 200 (POST 일 경우엔 201) 으로 설정된다. 이를 바꾸기 위해서는 @HttpCode(...)
decorator 를 이용할 수 있다.
library-specific (e.g., Express)를 이용하는 경우, Res()
decorator 를 method handler 를 통해 이용할 수 있다. (e.g., findAll(@Res() response
).
$npm install --save @types/express
- type definition for express
@Req()
를 통해 request object 에 접근할 수 있다.
Nest에서 services, repositories, factories, helpers와 같은 class들은 Provider로 취급된다.
controller 는 HTTP request를 처리하고, 더 복잡한 업무들은 providers에게 할당할 수 있다.
$ nest g service cats
component를 구성하기 위한 효과적인 방법
@Module
은 하나의 object를 가진다.
providers
: the providers that will be instantiated by the Nest injector and that may be shared at least across this module
controllers
: the set of controllers defined in this module which have to be instantiated
imports
: the list of imported modules that export the providers which are required in this module
exports
: the subset of providers
that are provided by this module and should be available in other modules which import this module