nest cli는 많은 기능을 제공하는 데, 그중 generator를 이용하여 CRUD를 구현해 보겠습니다.

먼저 nest -h 명령어를 통해 nest에서 사용하는 alias를 확인해 볼게요.

nest -h
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.
    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   │ 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                 │
      └───────────────┴─────────────┴──────────────────────────────────────────────┘

맨 아래에 보시면 CRUD가 있습니다. resource 또는 res를 이용하면 CRUD에 필요한 템플릿을 만들 수 있습니다.

저는 auth라는 CRUD 기능을 만들어 보겠습니다.

nest g res auth 
? What transport layer do you use? 
> REST API
  GraphQL (code first)
  GraphQL (schema first)
  Microservice (non-HTTP)
  WebSockets
? Would you like to generate CRUD entry points? (Y/n) Y
CREATE src/auth/auth.controller.spec.ts (556 bytes)
CREATE src/auth/auth.controller.ts (883 bytes)  
CREATE src/auth/auth.module.ts (240 bytes)      
CREATE src/auth/auth.service.spec.ts (446 bytes)
CREATE src/auth/auth.service.ts (607 bytes)
CREATE src/auth/dto/create-auth.dto.ts (30 bytes)
CREATE src/auth/dto/update-auth.dto.ts (164 bytes)
CREATE src/auth/entities/auth.entity.ts (21 bytes)
UPDATE src/app.module.ts (388 bytes)

nest g res 명령 실행 시 어떤 전송방법을 사용할지, CRUD point를 생성할지에 대해 물어봅니다.

저는 REST API, Y를 선택하여 생성하였습니다. 이제 start를 해보겠습니다.

 yarn start

"Nest application successfully started" 성공적으로 시작했다고 합니다.

"http://localhost:3000/auth"로 접속해 보니 "Hello" 메시지를 정상적으로 만나볼 수 있습니다.

하지만 우리는 이걸 목적으로 한 것이 아니기에 "http://localhost:3000/auth/1"로 접속해 봅니다.

이렇게 나오게 되면, Resource생성이 정상적으로 완료되었음을 확인할 수 있습니다.

생성된 폴더 구조를 살펴보도록 하겠습니다.

.ts파일 중 spec.ts는 테스트 파일, dto, entities폴더에 있는 파일은 DB와 관련된 파일입니다.

먼저 이외의 controller, moduel, service에 대해서 살펴보겠습니다.

 

> service

service파일은 비즈니스 로직을 처리하는 파일입니다. auth.service.ts의 AuthService를 살펴보면

create, findAll, findOne, update, remove라는 메서드가 있습니다.

방금 전, "http://localhost:3000/auth/1"를 호출하였을 때 만났던 메시지가 findOne 메서드를 통해 response 되었겠네요.

findOne(id: number) {
    return `This action returns a #${id} auth`;
  }

> controller

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post()
  create(@Body() createAuthDto: CreateAuthDto) {
    return this.authService.create(createAuthDto);
  }

  @Get()
  findAll() {
    return this.authService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.authService.findOne(+id);
  }

controller를 살펴보면 @Get, @Post, @Delete, @Patch와@Controller('auth') 데코레이터들을 볼 수 있습니다.

"localhost:3000/auth"로 request 하면 이 클래스에서 처리한다는 의미이고, 데코레이터들을 기준으로 각 메서드들이 처리함을 의미합니다. 

"http://localhost:3000/auth/1"를 호출하였을 때 service 중 findOne메서드를 통해 메시지가 출력되었는데, controller에서는 @Get(':id')인 데코레이터를 가진 findOne이 호출되어 service를 호출한 것입니다.

':'으로 시작하는 문자열이 파라미터 값이구나 하는 걸 직관적으로 알 수 있으시겠죠?

 

> module

@Module({
  controllers: [AuthController],
  providers: [AuthService]
})
export class AuthModule {}

auth.module.ts를 살펴보면 굉장히 간단하지만 중요한 역할을 합니다.

auth폴더 내에 있는 resource들을 어떻게 이용하겠다!라고 선언해주는 부분이기 때문입니다.

controller는 AuthController를, providers는 AuthService를 이용한다는 의미입니다. 

마지막으로 AuthModule로 export 하여주는데, 이는 프로젝트 전체의 app.module.ts에서 확인해보면

@Module({
  imports: [SharedModule, AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

"imports: [ "부분에 AuthModule이 import 되어 이용되는구나 확인할 수 있습니다.

 

 

728x90
반응형

'NestJS' 카테고리의 다른 글

[NestJS] swagger에서 테스트하기  (0) 2022.03.23
[NestJS] Authentication 구현  (0) 2022.03.18
[NestJS] app.controller 살펴보기  (0) 2022.03.02
[NestJS] 개발하기  (0) 2022.02.25
[NestJS] 시작하기  (0) 2022.02.25

+ Recent posts