심심한 개발자의 취미생활

Nest.js

  • Nest는 효율적이고 확장 가능한 Node.js 서버 측 애플리케이션을 구축하기 위한 프레임워크이다.
  • Nest는 기본적으로 Express.js를 기반으로 작동하지만 Fastify로 변경이 가능하다.

Nest Project 구축

NestCLI 스타터 프로젝트

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

Git 기반의 TypeScript 스타터 프로젝트

>> git clone https://github.com/nestjs/typescript-starter.git project
>> cd project
>> npm install
>> npm run start

기본 구조

my-project/
├ src/
| ├ app.controller.spec.ts
| ├ app.controller.ts
| ├ app.module.ts
| ├ app.service.ts
| └ main.ts
| 
  • app.controller.ts

    • 단일 경로를 가진 기본 컨트롤러
  • app.contoller.spec.ts

    • Controller에 대한 단위 테스트
  • app.module.ts

    • 애플리케이션의 루트 모듈
  • app.service.ts

    • 단일 방법을 제공하는 기본 서비스
  • main.ts

    • 핵심 기능을 사용하는 애플리케이션의 항목 파일, NestFactory Nest 애플리케이션 인스턴스를 생성
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
    // AppModule로 부터 정의된 모든 컨트롤러, 서비스, 다른 모듈들을 종합하여 애플리케이션 객체를 인자로 받아, 애플리케이션을 생성하고 구성한다.
    const app = await NestFactory.create(AppModule);

    // 지정된 포트로 부터 들어오는 HTTP 요청을 수신대기 하며 Nest 애플리케이션은 실행 상태가 되어 API 호출에 응답할 준비를 한다.
    await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • main.ts는 전체 애플리케이션을 시작하는 부트스트랩(bootstrap) 스크립트이다.
  • main.tsNestFactory를 사용해 루트 모듈(AppModule)로 부터 애플리케이션 인스턴스를 받고, 서버를 실행시켜 외부 요청을 받을 준비를 한다.

Platform

  • Nest는 플랫폼에 구애 받지 않느 프레임워크를 목표로 한다.
  • Nest에서 지원되는 HTTP 플랫폼은 expressfestify 두 가지가 있다.
    • platform-express : Express는 노드를 위한 유명한 미니멀 리스트 웹 프레임워크이며 Nest에서 기본 설정으로 지원한다.
    • platform-fastify : fastify는 최고의 효율성과 속도를 제공하는 데 중점을 둔 고성능 및 낮은 오버헤드 프레임워크이다.
    • const app = await NestFactory.create<NestExpressApplication>(AppModule);

Nest CLI

  • nest g [ order | alias ] [ name ]
order alias description
application application Generate a new application workspace
class cl Generate a new class
configuration config Generate a CLI configuration file
controller co Generate a controller declaration
decorator d Generate a custom decorator
filter f Generate a filter declaration
gateway ga Generate a gateway declaration
guard gu Generate a guard declaration
interceptor itc Generate an interceptor declaration
interface itf Generate an interface
library lib Generate a new library within a monorepo
middleware mi Generate a middleware declaration
module mo Generate a module declaration
pipe pi Generate a pipe declaration
provider pr Generate a provider declaration
resolver r Generate a GraphQL resolver declaration
resource res Generate a new CRUD resource
service s Generate a service declaration
sub-app app Generate a new application within a monorepo