[Nest.js]시작하기

[Nest.js]시작하기

Nest.js란?

nest js는 node js의 경량화된 웹 프레임워크인 Express js를 대규모 애플케이션 개발에 용이하도록 발전시킨 버전이라고 생각하면 된다. 자바에서 흔하게 사용되는 OOP. DI 등의 개념이 추가되어 자바스럽게 프로그래밍이 가능하다.

이때 Next.js와 혼동하는 경우가 많은데 next js는 리액트 기반 SSR 프레임워크를 뜻하고 Nest.js는 node js기반의 서버 사이드 웹 프레임워크로 서로 다른 프레임워크임을 알아야 합니다.

Nest.js 시작하기

1. nest.js CLI 도구 설치

nest js에서는 CLI 도구를 제공하므로 전역에 해당 도구를 설치합니다.

$ npm i -g @nestjs/cli

이를 통해 터미널에서 nest라는 명령어를 사용할 수 있습니다.


$ nest
nest
Usage: nest <command> [options]

Options:
  -v, --version                                   Output the current version.
  -h, --help                                      Output usage information.

Commands:
  new|n [options] [name]                          Generate Nest application.
  build [options] [app]                           Build Nest application.
  start [options] [app]                           Run Nest application.
  info|i                                          Display Nest project details.
  add [options] <library>                         Adds support for an external library to your project.
  generate|g [options] <schematic> [name] [path]  Generate a Nest element.
    Schematics available on @nestjs/schematics collection:
      ┌───────────────┬─────────────┬──────────────────────────────────────────────┐
      │ name          │ 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                        │
      │ 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      │
      │ service       │ s           │ Generate a service declaration               │
      │ library       │ lib         │ Generate a new library within a monorepo     │
      │ sub-app       │ app         │ Generate a new application within a monorepo │
      │ resource      │ res         │ Generate a new CRUD resource                 │
      └───────────────┴─────────────┴──────────────────────────────────────────────┘

2. nest 프로젝트 생성

nest new 명령어 뒤에 생성할 디렉토리명을 적습니다. 그러면 사용할 package manager를 선택하라고 목록이 표시됩니다. 저는 npm을 선택해 진행했습니다.

$ nest new myNestJs
⚡  We will scaffold your app in a few seconds..

? Which package manager would you ❤️  to use? (Use arrow keys)
❯ npm
  yarn
  pnpm

아래는 프로젝트 생성 결과입니다.

CREATE my-nest-js/.eslintrc.js (688 bytes)
CREATE my-nest-js/.prettierrc (54 bytes)
CREATE my-nest-js/nest-cli.json (179 bytes)
CREATE my-nest-js/package.json (2018 bytes)
CREATE my-nest-js/README.md (3413 bytes)
CREATE my-nest-js/tsconfig.build.json (101 bytes)
CREATE my-nest-js/tsconfig.json (567 bytes)
CREATE my-nest-js/src/app.controller.ts (286 bytes)
CREATE my-nest-js/src/app.module.ts (259 bytes)
CREATE my-nest-js/src/app.service.ts (150 bytes)
CREATE my-nest-js/src/main.ts (216 bytes)
CREATE my-nest-js/src/app.controller.spec.ts (639 bytes)
CREATE my-nest-js/test/jest-e2e.json (192 bytes)
CREATE my-nest-js/test/app.e2e-spec.ts (654 bytes)

✔ Installation in progress... ☕

🚀  Successfully created project my-nest-js
👉  Get started with the following commands:

$ cd my-nest-js
$ npm run start


                          Thanks for installing Nest 🙏
                 Please consider donating to our open collective
                        to help us maintain this package.


               🍷  Donate: https://opencollective.com/nest

보시는 것과 같이 저는 myNestJs라는 이름의 디렉토리를 만들고 싶었지만 자동으로 하이픈을 이용한 이름으로 변경되었네요. 아마도 대문자를 사용할 수 없는 것 같습니다.

3. 프로젝트 시작

위 결과에 따라 cd my-nest-js 명령어를 통해 새롭게 생성된 디렉토리에 접속 후 npm run start 명령어를 실행합니다.

localhost의 3000포트로 nest js 애플리케이션이 구동되는 모습을 확인할 수 있습니다.

4. 프로젝트 구조

디렉토리 구조는 다음과 같습니다.

  • Nest JS 디렉토리명
    • dist
    • node_modules
    • src
    • test
    • .eslintrc.js
    • .gitignore
    • .prettierrc
    • nest-cli.json
    • package-lock.json
    • package.json
    • README.md
    • tsconfig.build.json
    • tsconfig.json

주요한 부분은 src 디렉토리 하위에 존재합니다. Nest JS는 흔하게 사용되는 MVC 디자인 패턴을 기반으로 구조가 설계되어있습니다. 크게 구조는 3가지 부분인 모듈(Module), 컨트롤러(Controller), 서비스(Service)로 나뉘어 있습니다.

  1. 모듈(Modules) - src / app.modules.ts @Modules() 데코레이터를 이용해 구현되며 애플리케이션의 기능별로 나뉘어진 묶음 단위를 모듈이라고 생각하면 된다. 모듈 구성 요소는 다음과 같다.
    • imports : 의존성 주입. A모듈이 B모듈을 사용할 수 있도록 하기 위해서는 A모듈 imports 부분에 B모듈을 넣어 모듈을 결합할 수 있다.
    • controllers : 컨트롤러 클래스 명시.
    • providers : 해당 모듈에서 사용되는 모듈 이외의 provider 명시. 주로 서비스 클래스 명시.
    • exports: 외부 모듈에서 해당 모듈을 import했을 때 사용할 수 있는 클래스 명시.
  2. 컨트롤러(Controller)- src / app.controller.ts @Controller() 데코레이터를 이용해 구현되며 HTTP 요청을 받고 응답을 해주는 역할이다. @Get(), @Post(), @Delete() 등의 데코레이터를 이용해 상세하게 구현된다.

  3. 서비스(Service)- src / app.service.ts @Injectable() 데코레이터를 이용해 구현되며 비즈니스 로직을 처리하는 역할이다. 주로 컨트롤러에서 호출되어 사용된다.

5. 예시 - 로그인 기능 구현해보기

로그인 기능을 구현하기 위해 전체적으로 필요한 부분을 생각해보았다.

  • DTO, Entity
  • Service
  • Controller
  • JWT(JSON Web Token)

users 폴더 생성하기

먼저 src 폴더 하위에 users와 auth라는 이름의 폴더 2개를 생성했다. 사용자와 인증에 대한 모듈을 따로 생성하기 위함. 또한 해당 폴더 하위에는 dto, controller, service, module 파일 및 폴더를 생성했다.

src/
│
├── auth/              # 인증 관련 모듈
│   ├── dto/           # 데이터 전송 객체
│   │   ├── login.dto.ts
│   │   └── register.dto.ts
│   ├── auth.controller.ts
│   ├── auth.module.ts
│   ├── auth.service.ts
│   ├── jwt.strategy.ts
│   └── local.strategy.ts
│
├── users/             # 사용자 관련 모듈
│   ├── dto/           # 데이터 전송 객체
│   │   └── create-user.dto.ts
│   ├── entities/      # 데이터베이스 엔티티
│   │   └── user.entity.ts
│   ├── users.controller.ts
│   ├── users.module.ts
│   └── users.service.ts
│
├── app.controller.ts  # 애플리케이션의 기본 컨트롤러
├── app.module.ts      # 애플리케이션의 루트 모듈
└── main.ts            # 애플리케이션의 엔트리 포인트

####

results matching ""

    No results matching ""