재학습/NestJS

[NestJS] 기본파일체크와 Generate의 신기함(?)

재삉 2022. 12. 11. 02:33
반응형


Check Default File

  1. main.ts
  2. app.module.ts
  • @module이라는 데코레이터를 볼 수 있다.
  • 루트 모듈
  1. app.controller.ts
  • @get이라는 데코레이터를 볼 수 있다.
  • appService의 getHello()를 리턴한다.
  1. app.service.ts
  • @Injectable이라는 데코레이터를 볼 수 있다.
  • 문자열 "Hello World"를 출력한다.
  • 데코레이터 = Spring의 어노테이션 기능을 하는 것 같다.
  • 모듈이란 ?
  • 한가지 역할을 하는 앱, 컴포넌트 요런 느낌

App Module

  • 루트 모듈
  • 어플리케이션 접근점
  • AppController, AppProvider를 가지고있어야 함

Controller

  • URL을 가져오고 함수 리턴(URL과 함수 매핑)
  • @Get (express의 Get라우터)
  • @Get("/hello")로 만든 함수는 localhost:3000/hello 에 해당되는 결과를 반환하게된다.
  • Parameter 사용
  1. @Get(":id")
  2. getOne(@Param('id') id): type
  3. { return id is ${id} }
  • QueryString 사용
  • getOne(@Query('id') id): type

Service

  • Controller <-> 비지니스 로직 구분을 위한 단계
  • 실질적인 Function, 비지니스로직
  • Single-Responsibility Principle을 따르자

반응형

 

그리고 재밌는기능, 여타 다른 프레임워크에서는 항상 해줘야하는 Controller, Service등의 생성 루틴을 커맨드로 커버 가능하다.

커맨드 상에 nest로 치면 관련 명령어를 확인 할 수 있다.

command % 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                 │
      └───────────────┴─────────────┴──────────────────────────────────────────────┘

 

Generate

  • Nest 프로젝트 개발을 위한 커맨드
  • Ex) 컨트롤러 생성
  1. nest generate controller ( = nest g co )
  2. input controller name
  • 그러면 벌어지는 일
  1. AppModule에 Controller 자동추가
  2. src/movies 디렉토리 자동생성
  3. src/movies/movies.controller.ts 파일 자동생성
  • nest generate service 도 가능
  • nest generate module 도 가능 .. 등등 많음 (커맨드에 nest치면 목록 나옴)
  • Spec파일? 테스트를 위한 파일. 일단 보류

 

Generate 수행

1.Command :: generate controller movies

 

2.Before :: app.module.ts

import { Module } from '@nestjs/common';

//아래의 형태는 데코레이터.
//Nest는 데코레이터와 함께한다.
//데코레이터는 클래스에 함수기능을 추가한다.
@Module({
  imports: [],
  controllers: [],
  providers: [],
})
//AppModule은 속이 비어있는형태

 

3.After :: app.module.ts

import { Module } from '@nestjs/common';
import { MoviesController } from './movies/movies.controller';

//아래의 형태는 데코레이터.
//Nest는 데코레이터와 함께한다.
//데코레이터는 클래스에 함수기능을 추가한다.
@Module({
  imports: [],
  controllers: [MoviesController],
  providers: [],
})
//AppModule은 속이 비어있는형태

 

4.After :: movies/ 디렉토리 하위에 controller, spec_controller 생성

반응형