Undergoing

01. Nest 본문

개발/Nest

01. Nest

Halkrine 2021. 8. 4. 16:08

1. What is Nest

- Node.js 서버측 app을 구축하기 위한 framework

- TypeScript로 build 되지만 순수 자바스크립트로도 코딩 가능

- OOP, FP, FRP 요소가 결합

- 서버 프레임워크로는 Express를 기본으로 사용, 선택적으로 Fastify를 사용하도록 구성할 수 있음

- Angular, React, Vue 등과 어울림. 

- TypeScript + Spring Framework가 결합된 느낌이 듦

 

2. Nest 학습 시작 배경

- Spring Framework 외의 서버 개발 기법 학습 및 도입

- Node.js 학습을 하다가 알게 됨. Node.js는 따로 보면서 병행할 예정

- 튜토리얼로만 봤을 때 어느 정도 Spring과 비슷한 문법이 보여 Tyscript 숙지와 병행할 수 있음을 기대

- 서버 구축 측면에서 보면 Spring 보다 러닝 커브가 적음

- Node 개발 경험 습득

 

3. 설치하기

- nest 설치

-> npm i -g @nestjs/cli

...
...
...
+ @nestjs/cli@8.1.1
added 263 packages from 246 contributors in 25.894s

->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.
  update|u [options]                              Update Nest dependencies.
  add [options] <library>                         Adds support for an external library to your project.
  generate|g [options] <schematic> [name] [path]  Generate a Nest element.
    Available schematics:
      ┌───────────────┬─────────────┬──────────────────────────────────────────────┐
      │ 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   │ in          │ Generate an interceptor declaration          │
      │ interface     │ interface   │ 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                 │
      └───────────────┴─────────────┴──────────────────────────────────────────────┘

- 새 프로젝트 생성

D:\IdeaProjects>nest new
⚡  We will scaffold your app in a few seconds..

? What name would you like to use for the new project? nest-app
CREATE nest-app/.eslintrc.js (631 bytes)
CREATE nest-app/.prettierrc (51 bytes)
CREATE nest-app/nest-cli.json (64 bytes)
CREATE nest-app/package.json (1964 bytes)
CREATE nest-app/README.md (3339 bytes)
CREATE nest-app/tsconfig.build.json (97 bytes)
CREATE nest-app/tsconfig.json (365 bytes)
CREATE nest-app/src/app.controller.spec.ts (617 bytes)
CREATE nest-app/src/app.controller.ts (274 bytes)
CREATE nest-app/src/app.module.ts (249 bytes)
CREATE nest-app/src/app.service.ts (142 bytes)
CREATE nest-app/src/main.ts (208 bytes)
CREATE nest-app/test/app.e2e-spec.ts (630 bytes)
CREATE nest-app/test/jest-e2e.json (183 bytes)

? Which package manager would you ❤️  to use? npm
√ Installation in progress... ☕

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

$ cd nest-app
$ 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

입력한 프로젝트명으로 관련 dir 생성. package는 npm, yarn, pnpm 셋 중 하나를 선택하게 되어있는데 나는 npm으로 설정. 

 

위 과정이 귀찮으면 github에서 clone을 딸 수도 있음

 

IDE로 로드했을 때 다음과 같은 구조면 정상적으로 생성 완료되었음을 나타냄. 

4. Nest 구조

기본 생성 시 다음과 같은 구조로 생성됨(IDE 설정성 파일 제외)

Project
├ src
│ ├ test
│ ├ app.controller.spec.ts
│ ├ app.controller.ts
│ ├ app.module.ts
│ ├ app.service.ts
│ └ main.ts

├ test
│ ├ app.e2e-spec.ts
│ └ jest-e2e.json

├ ...
├ nest-cli.json
├ package.json
├ package-lock.json
├ README.md
├ tsconfig.build.json
└ tsconfig.json
  • app.controller.ts : 하나의 router가 존재하는 기본 Controller
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}
  • app.controller.spec.ts : Unit Test
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';

describe('AppController', () => {
  let appController: AppController;

  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      controllers: [AppController],
      providers: [AppService],
    }).compile();

    appController = app.get<AppController>(AppController);
  });

  describe('root', () => {
    it('should return "Hello World!"', () => {
      expect(appController.getHello()).toBe('Hello World!');
    });
  });
});
  • app.module.ts : app의 root module
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  • app.service.ts : 단일 method를 사용하는 기본 Service
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}
  • main.ts : NestFactory를 사용, nest App instance를 생성하는 App의 entry file로, App을 Bootstrap하는 비동기 함수가 포함됨. npm run start 시 이 파일에 정의된 포트(하단 소스에서는 3000)에서 수신대기하는 HTTP로 앱을 시작함
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

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

적어도 Controller-Service 간의 관계는 기존 Spring과 유사하여 Spring 유저라면 도입부에 대한 이해는 크게 어렵지 않다고 생각함. 단 TypeScript에 대한 이해는 같이 해야 기능 구현을 할 수 있음(Javascript로도 가능하긴 함)

 

 

 

Nestjs 공식 사이트

'개발 > Nest' 카테고리의 다른 글

03. Next.js 붓기  (0) 2021.08.12
02. Nest - PostgreSQL 연동  (0) 2021.08.10