Nest.js 기본 구성

0

Nest.js 시작 가이드

Nest.js 프로젝트를 처음 시작할 때 필요한 설치부터 Controller, Service, Module 생성 방법까지 정리한 문서입니다.


📦 1. Nest CLI 설치

Nest.js를 시작하려면 Nest CLI를 전역 설치해야 합니다.

npm i -g @nestjs/cli

🚀 2. 새 프로젝트 생성

nest new my-nest-app
  • 설치 중에 npm 또는 yarn 선택 가능
  • my-nest-app이라는 폴더가 생성됩니다.

🗂️ 3. 기본 폴더 구조

src/
├── app.controller.ts // 기본 Controller
├── app.service.ts // 기본 Service
├── app.module.ts // 루트 Module
├── main.ts // 앱 시작점

🛠️ 4. 컨트롤러 / 서비스 / 모듈 생성 방법

✅ 컨트롤러 생성

nest generate controller board
# 또는 줄여서
nest g co board

✅ 서비스 생성

nest generate service board
# 또는 줄여서
nest g s board

✅ 모듈 생성

nest generate module board
# 또는 줄여서
nest g mo board

생성 구조:

src/board/
├── board.controller.ts
├── board.service.ts
└── board.module.ts

5. 추가로 설치하면 좋은 패키지

기능설치 명령어설명
유효성 검사npm i class-validator class-transformerDTO에 유효성 검사 데코레이터 사용 가능
Swagger 문서화npm i @nestjs/swagger swagger-ui-expressAPI 문서를 자동 생성
MongoDB 연동npm i mongoose @nestjs/mongooseMongoose ODM 연동
PostgreSQL 연동npm i @nestjs/typeorm typeorm pgTypeORM + PostgreSQL 연동

Swagger

Installation

$ npm install --save @nestjs/swagger
  • main.ts
	
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';

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

  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('board')
    .build();
  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, documentFactory);

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • Board.controller.ts
@Controller('board')
@ApiTags('board')
export class BoardController {
profile
하루하루 기록하기!

0개의 댓글