첫 단추로 Nest의 가장 핵심 기능을 알아 볼 것이다. 가장 기본적인 CRUD에 대해 알아 보자.

Language

주로 TypeScript를 사용할 것이고, 또한 Node.js를 애착한다. 그렇기에 Nest는 Typescript과 pure Javascript 둘 다 양립가능하다. Nest는 가장 최근의 language feature들의 이점을 가져온다. 그래서 vanilla JavaScript와 함께 사용하기 위해 Nest는 Babel compier를 사용한다.

Vanilla JS: 외부의 라이브러리나 프레임워크를 이용하지 않는 순수 자바스크립트를 말한다.
    둘을 사용하지 않기에, 사용했을 때 보다 호환성이 좋다는 게 특징이다. 이런 특징은 디버그(Debug)를 할 때 유용하다. 

Babel Compiler: Javascript 코드를 컴파일하는 도구로, 최신 JS 문법과 기능을 이전 버전의 JS로 변환해준다. 
    이를 통해 최신 Javascript 기능을 지원하지 않는 구형 브라우저나 환경에서도 최신 코드를 사용할 수 있게 해준다.

Prerequisites

사용자의 OS에는 Node.js(version >= 16)이 설치되어야 한다.

Setup

새 프로젝트를 setting하는데는 Nest CLI를 이용하여 꽤 간단하다.

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

만일 TypeScript의 stricter한 feature set으로 설치하고자 한다면, --strict flag를 nest new command에 덧붙인다.

project-name 디렉토리가 만들어 질 것이며, node modules와 다른 boliderplate files들이 설치될 것이다. 그리고 src/ 디렉터리가 또한 만들어 질 것이며 아래와 같이 핵심 파일들이 있다.

src
    app.controller.spec.ts
    app.controller.ts
    app.module.ts
    app.service.ts
    main.ts

각 파일의 역할은 다음과 같다.

files description
app.controller.ts a single route가 있는 간단한 controller
app.controller.spec.ts controller를 위한 간단한 unit test를 위함
app.module.ts application의 root module
app.service.ts single method가 포함된 가장 기본적인 service
main.ts NestJs application의 진입 파일(entry file)에 대한 것이다. 핵심 함수인 NestFactory를 사용하여 Nest application instance를 생성한다.

main.ts는 동기 함수, bootstrap이 포함되어 있다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

Nest Application instance를 만들기 위해, NestFactory class를 사용한다. NestFactory는 application instance를 만들기 위한 여러 개의 method를 제공한다. create()는 application object를 반환한다. 이는 INestApplication interface에 따라진다. main.ts에서는 HTTP listener를 시작하여 애플리케이션이 들어오면 HTTP 요청을 대기하도록 한다.

Nest CLI에 기반된 project는 초기 프로젝트 structure를 만든다. 이는 개발자들이 각 모듈의 관습을 따르도록 장려한다.

//기본적으로, 애플리케이션이 생성되는 동안 오류가 발생하면, 애플리케이션은 코드 1과 함께 종료된다. 이 기본 동작을 변경하여 오류를 발생시키도록하고 싶다면, `abortOnError` 옵션을 비활성화하면 된다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  try {
    const app = await NestFactory.create(AppModule, { abortOnError: false });
    // abortOnError: 이 옵션을 사용하면 애플리케이션이 종료되지 않고 오류를 던진다.
    // abort: 중단하다.
    await app.listen(3000);
  } catch (error) {
    console.error('Error starting the application:', error);
  }
}
bootstrap();

Platform

Nest는 플랫폼 종속적이지 않은 프레임워크를 지향한다. Platform independence는 framework로써 NestJs는 코드의 재사용성을 높여준다. 즉, 특정 플랫폼에 종속되지 않기에, 한 번 작성한 논리적 모듈이나 컴포넌트를 다양한 애플리케이션에서 다시 사용할 수 있다. 이는 개발 생산성을 높이고, 유지보수를 용이하게 한다. 기술적으로, Nest는 adapter가 만들어지면 어떤 Node HTTP framework라도 작동한다.
두 개의 HTTP platform이 있다. expressfastify가 있다.

플랫폼 독립적
1. 운영 체제 독립성: window, macOS, Linux...
2. 서버 프레임워크 독립성: Express, Fastify 등 다양한 HTTP 서버 프레임워크와 호환되어 사용할 수 있다.
3. 클라우드 플랫폼 독립성: 애플리케이션이 AWS, Google Cloud, Azure 등 다양한 클라우드 서비스 제공업체에서
    문제없이 배포되고 실행될 수 있다. 
HTTP platform description
platform-express Express는 node를 위한 잘 알려진 web framework다. 이는 많은 테스트를 거친, 프로덕션 준비가 된 라이브러리다. 커뮤니티에서 구현한 많은 리소스를 포함하고 있다. @nestjs/platform-express package가 기본적으로 사용된다. 많은 사용자들이 Express로 서비스를 제공받고 있으며, 이를 활성화하기 위해 별도의 작업이 필요치 않다.
platform-fastify Fastify는 높은 성능과 낮은 overhead의 framework이다. 이는 높은 효율성과 속도를 제공해준다.
Express: 웹 및 모바일 애플리케이션을 위한 일련의 강력한 기능을 제공하는 간결하고 
    유연한 Node.js 웹 애플리케이션 프레임워크이다. 즉 Node.js를 사용하여 쉽게 서버를 구성할 수 있게
    만든 클래스와 라이브러리의 집합체이다.

Fastify: Node.js를 위한 빠르면서도 오버헤드가 적은 웹 프레임워크이다.

어떤 플랫폼을 사용하든지, 이는 각자의 application interface를 나타낸다. 이는 각각 NestExpressApplicationNestFastifyApplication 사용된다.

만일 NestFactory.create() method를 사용할 때, (아래와 같이) app 객체는 specifc platform에 맞는 method들을 가질 것이다. 하지만 실제로 해당 platform API에 접근하려는 경우가 아니면 타입을 지정할 필요는 없다. 즉 특정 platform의 API를 사용하고 싶다면 타입을 지정한다.

  1. 기본 사용법(타입 지정 없음)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

bootstrap();
  1. 타입 지정(Express)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.set('trust proxy', 1); // Express 고유의 메서드 사용 예시
  await app.listen(3000);
}

bootstrap();
  1. 타입 지정(Fastify)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestFastifyApplication } from '@nestjs/platform-fastify';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(AppModule);
  app.register(require('fastify-cors')); // Fastify 고유의 메서드 사용 예시
  await app.listen(3000);
}

bootstrap();

Running the application

설치 과정이 완료되면, 다음 명령어를 운영 체제의 명령 프롬프트에서 실행하여 애플리케이션이 들어오는 HTTP 요청을 대기하도록 시작할 수 있다.

npm run start

<팁!>
만일 process의 build 속도(x20 times faster build)를 높이고자한다면, SWC builder 를 사용할 수 있다. -b swc flag를 start script에 추가하면된다. npm run start -- -b swc

위의 command는 HTTP server가 src/main.ts에 정의된 port에서 대기하도록 한다. application을 running하고 브라우저에서 'http://localhost:3000/' 접속하면 'Hello word!' 메시지를 볼 수 있다.

src의 파일을 바꿀 때 변경사항을 바로바로 확인하고 싶다면 아래의 command로 시작한다.

$ npm run start:dev

이 command는 file의 변경 사항을 자동으로 recompile하고 server를 reloading한다.

Linting and formatting

CLI는 개발함에 있어 최고의 여건을 마련해준다.
생성된 Nest projects linterformatter의 code가 함께 설치된다. 이는 각각 eslintprettier이다.

code linter: 코드의 일관성과 스타일을 유지하고, 잠재적인 오류를 발견하기 위해 코드 품질을 검사하는 도구이다. 
    Nest 프로젝트는 eslint가 사용된다.
code formatter: 코드의 형식을 자동으로 맞춰주는 도구이다. Nest 프로젝트에서는 prettier가 사용된다.

안정성(stability)와 확장성(extensibility)을 보장해주기 위해, eslintprettier package가 사용된다.
이는 공식적인 extenstions을 통해 정돈된 IDE 완성을 시켜준다.

headless 환경에서, IDE가 필요 없는 환경에서는 바로 사용할 수 있는 npm 스크립트를 제공한다.

# Lint and autofix with eslint
$ npm run lint

# Format with prettier
$ npm run format
  • headless environment: IDE(통합 개발 환경)을 사용하지 않고, 주로 명령줄에서 작업하는 환경을 의미한다.
  • npm script: package.json 파일에 정의된 명령어로, 프로젝트의 빌드, 테스트, lint 등의 작업을 자동화하는 데 사용된다.
{
  "scripts": {
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:prod": "node dist/main",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  }
}

'NestJS > Docs_OVERVIEW' 카테고리의 다른 글

Exception filters  (0) 2024.06.05
Middleware  (1) 2024.06.04
Modules  (1) 2024.06.04
Providers  (0) 2024.06.04
Controllers  (0) 2024.06.03

+ Recent posts