Nest.js

김가영·2021년 4월 6일
0

Node.js

목록 보기
26/34

Nest.js

  • express 기반 -> express middleware 사용 가능

  • 선택적으로 Fastify 사용 가능

  • 기본적으로 typescript 지원, pure Javscript 도 사용 가능

  • 구조를 가지고 있고, 순서와 룰도 있고

  • 모듈 간의 의존성이 명확

  • TypeScript 로 구축

  • 테스트 환경 제공, 확장성, 유지관리가 용이한 애플리케이션 아키텍쳐를 제공

시작하기

npm i -g @nestjs/cli
nest new project-name

neststudy 라는 prject를 생성하니

이러한 프로젝트 구조가 만들어졌다.

구조(src)

  • 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를 작동시켰다.

Controllers

  • request를 받고, response를 return 하는 것을 관리한다.

  • routing을 통해 어떤 controller가 어떤 request를 받을지 결정한다.

  • class와 decorator 를 이용할 거다. decorator는 class 와 metadata를 연결시키고, Nest가 routing map을 형성하게 만든다.

Routing

@Controller(): basic controller를 정의하기 위해 필요한 decorator
연관된 route들을 그룹화하고, 중복 코드를 방지하는 기능을 한다.

$ nest g controller controller_name 명령어를 통해 controller 를 생성할 수 있다.

  • cats.controller.ts

Nest js 가 Response 를 처리하는 방법

Standard(recommended)

request handler가 JS object 나 array 를 return 하면 자동으로 JSON 으로 바꿔준다. 하지만 JS Primitive Type 을 return 할 경우에는 값만 전송하기 때문에 더 간단해진다. 또한 status code 를 자동으로 200 (POST 일 경우엔 201) 으로 설정된다. 이를 바꾸기 위해서는 @HttpCode(...) decorator 를 이용할 수 있다.

Library-specific

library-specific (e.g., Express)를 이용하는 경우, Res() decorator 를 method handler 를 통해 이용할 수 있다. (e.g., findAll(@Res() response).

Request object

$npm install --save @types/express - type definition for express
@Req() 를 통해 request object 에 접근할 수 있다.

  • async, await 을 이용할 수도 있다. async function 은 Promise 를 return 한다.

POST

  • POST의 Body를 받기 위해서는 일단 DTO(Data Transfer Object) schema를 정의해야 한다. DTO schema 는 타입스크립트의 class 나 interface 를 이용하여 정의할 수 있으며, class를 사용하는 것이 추천된다.
  • App.module.ts

    자동으로 추가된다.

Library-specific

Providers

Nest에서 services, repositories, factories, helpers와 같은 class들은 Provider로 취급된다.

controller 는 HTTP request를 처리하고, 더 복잡한 업무들은 providers에게 할당할 수 있다.

Services

$ nest g service cats

  • cats.service.ts

Modules

  • 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

profile
개발블로그

0개의 댓글