NestJS - 셋업 + CRUD

Hunter Joe·2025년 2월 4일
0

Installation

npm i -g @nestjs/cli 
nest <<< 잘 깔려있나 help 같은 명령어 
nest new project-name

HINT
TS strict를 추가하고 싶다면 --strictflag를 같이 쓸 것
nest new project-name --strict

기본 폴더 구조

파일명설명
app.controller.ts단일 라우트를 가진 기본 컨트롤러.
app.controller.spec.ts컨트롤러의 단위 테스트 파일.
app.module.ts애플리케이션의 루트 모듈.
app.service.ts단일 메서드를 가진 기본 서비스.
main.tsNestFactory 를 사용해 애플리케이션 인스턴스를 생성하는 엔트리 파일.

처음 써보는 내가 분석해본 코드

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • Factory 패턴을 사용해서 인스턴스를 찍어내고 있구나 판단

// src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
/**
 * Decorator
 * nestjs를 사용할 때 데코레이터는 짝꿍 같은 존재
 * 데코레이터는 클래스에 함수 기능을 추가할 수 있다.
 */
@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
  • controller, service: controller는 route, service는 비지니스 로직을 뜻하겠군
  • 클래스형식으로 export하고 있구나.

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

/**
 * controller는 express.js의 controller/router같은 것
 */
@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get() // same as Express GET route
  getHello(): string {
    return this.appService.getHello();
  }

  // 데코레이터는 항상 클래스 or 함수에 붙어있어야한다. (Convention)
  @Get('/hello')
  getHi(): string {
    return this.appService.getHi();
  }
}
  • controller는 라우트의기능을 해주는거 같다.
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World! holy';
  }
  getHi(): string {
    return 'Hello fuccking everyone';
  }
}
  • injectable 뭔가를 주입하고 있구나
  • getHello(), getHi() 함수의 값을 return 하고 있구나

일단 맨 처음 주는 코드로 봤을 때 main.ts에서 팩토리 패턴을 활용해서 모듈을 찍어낼 수 있겠다. 라는 생각이 든다.
그리고 해당 module.tscontrollerservice를 분리해서 작성하고 있다.
즉, 라우터와 비즈니스 로직을 분리해서 작성하고 있다.
간단한 구조라고 생각듬

CRUD

1. controller만들기

  • NestJS는 폴더 구조 관련해서도 자동 CLI 제공
$ nest g co movies

2. CRUD

// src/movies.controller.ts
import { Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';

@Controller('movies')
export class MoviesController {
  @Get()
  getAll() {
    return 'this will return all movies';
  }

  @Get('/:id')
  getOne(@Param('id') movieId: string) {
    return `this will return one movie with the id : ${movieId}`;
  }

  @Post()
  create() {
    return 'this will create a movie';
  }

  @Delete('/:id')
  remove(@Param('id') movieId: string) {
    return `this will delete a movie with the id : ${movieId}`;
  }

  @Patch('/:id')
  patch(@Param('id') movieId: string) {
    return `this will update a movie with the id : ${movieId}`;
  }
}
  • 중요한 것 하나는 내가 무언가(params, body, header, etc ...)를 원하면 인자로 넣어서 요청을 해야한다.
    @Param : 파라미터 요청
profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글

관련 채용 정보