๐Ÿˆ

NestJS ์น˜ํŠธ์‹œํŠธ

TypeScript ๊ธฐ๋ฐ˜ ์—”ํ„ฐํ”„๋ผ์ด์ฆˆ Node.js ๋ฐฑ์—”๋“œ ํ”„๋ ˆ์ž„์›Œํฌ ์™„๋ฒฝ ๊ฐ€์ด๋“œ: ํ•„์ˆ˜ ์‚ฌ์ „ ์„ค์น˜ ์š”๊ฑด, ๋ชจ๋“ˆยท์ปจํŠธ๋กค๋Ÿฌยท์„œ๋น„์Šค ์•„ํ‚คํ…์ฒ˜ ๋ฐ ์˜์กด์„ฑ ์ฃผ์ž…(DI), ์š”์ฒญ ์ฒ˜๋ฆฌ ์ƒ๋ช…์ฃผ๊ธฐ(MiddlewareยทGuardยทInterceptorยทPipeยทFilter), DTO ์œ ํšจ์„ฑ ๊ฒ€์ฆ, TypeORM/Prisma ์—ฐ๋™, JWT ์ธ์ฆ ๋ฐ ํ”„๋กœ๋•์…˜ ์šด์˜ ์ฒดํฌ๋ฆฌ์ŠคํŠธ

--views
๋‹จ์ˆ˜:
#nestjs#typescript#nodejs#backend#dependency-injection#typeorm#prisma#jwt#swagger#rest-api์ตœ์ข… ์—…๋ฐ์ดํŠธ: 2026-10-08

1. ํ•„์ˆ˜ ์‚ฌ์ „ ์„ค์น˜ ์š”๊ฑด & ๊ฐœ๋ฐœ ํ™˜๊ฒฝ ๊ตฌ์„ฑ (Prerequisites)

๐Ÿ’ป ์‹œ์Šคํ…œ ์„ค์น˜ ๋ฐ ์‹คํ–‰ ์š”๊ตฌ์‚ฌ์–‘ (System Requirements)

ํ•ญ๋ชฉ์ตœ์†Œ ์‚ฌ์–‘ (Minimum)๊ถŒ์žฅ ์‚ฌ์–‘ (Recommended)์ฐธ๊ณ  ๋ฐ ๋น„๊ณ 
์šด์˜์ฒด์ œ (OS)Linux, macOS, Windows 10/11Ubuntu 22.04 LTS, macOS (Apple Silicon), Windows 11Node.js ๊ตฌ๋™ ๊ฐ€๋Šฅ OS
CPU1 ์ฝ”์–ด ์ด์ƒ2 ์ฝ”์–ด ~ 4 ์ฝ”์–ด ์ด์ƒTypeScript ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ๋ฆฌํ”Œ๋ ‰์…˜ ๋ฐ ๋นŒ๋“œ
๋ฉ”๋ชจ๋ฆฌ (RAM)1 GB ์ด์ƒ2 GB ~ 4 GB ์ด์ƒSWC/Webpack ๋ฒˆ๋“ค๋Ÿฌ ๋ฐ ๋Ÿฐํƒ€์ž„ DI ์ปจํ…Œ์ด๋„ˆ
๋””์Šคํฌ (Storage)1 GB ์ด์ƒ์˜ ์—ฌ์œ  ๊ณต๊ฐ„5 GB ์ด์ƒ์˜ SSDnode_modules ๋ฐ dist ์ปดํŒŒ์ผ ๋””๋ ‰ํ† ๋ฆฌ
๋„คํŠธ์›Œํฌ / ๋Ÿฐํƒ€์ž„Node.js 18, 20, 22 LTSnpm, pnpm ๋˜๋Š” yarnNest CLI (npm i -g @nestjs/cli)

NestJS๋Š” TypeScript๋ฅผ ๊ธฐ๋ณธ ์–ธ์–ด๋กœ ์ฑ„ํƒํ•œ ์ง„๋ณด๋œ Node.js ์—”ํ„ฐํ”„๋ผ์ด์ฆˆ ๋ฐฑ์—”๋“œ ํ”„๋ ˆ์ž„์›Œํฌ์ž…๋‹ˆ๋‹ค. Spring Boot์™€ ์œ ์‚ฌํ•œ ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ(OOP), ํ•จ์ˆ˜ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ(FP), ํ•จ์ˆ˜ ๋ฐ˜์‘ํ˜• ํ”„๋กœ๊ทธ๋ž˜๋ฐ(FRP) ์š”์†Œ์™€ ๊ฐ•๋ ฅํ•œ ์˜์กด์„ฑ ์ฃผ์ž…(DI) ์‹œ์Šคํ…œ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.

๐ŸŸข 1. Node.js ๋Ÿฐํƒ€์ž„ ๋ฒ„์ „ & ๋ฒ„์ „ ๊ด€๋ฆฌ์ž

NestJS๋Š” Node.js 18.x, 20.x, 22.x LTS ์ด์ƒ ํ™˜๊ฒฝ์„ ํ•„์š”๋กœ ํ•ฉ๋‹ˆ๋‹ค.

# 1. Node.js ๋ฒ„์ „ ํ™•์ธ (v18.0.0 ์ด์ƒ ํ•„์ˆ˜, ๊ถŒ์žฅ: v20.x ๋˜๋Š” v22.x LTS)
node -v
npm -v

# 2. Node ๋ฒ„์ „ ๊ด€๋ฆฌ์ž(fnm ๋˜๋Š” nvm)๋ฅผ ํ†ตํ•œ ์ตœ์‹  LTS ์„ค์น˜ (Windows / macOS / Linux)
# fnm ์‚ฌ์šฉ ์‹œ (์ดˆ๊ณ ์† ๊ถŒ์žฅ)
fnm install --lts
fnm use lts-latest

# nvm ์‚ฌ์šฉ ์‹œ
nvm install --lts
nvm use --lts

๐Ÿ› ๏ธ 2. NestJS CLI ์„ค์น˜ ๋ฐ ์ƒˆ ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ

๊ณต์‹ Nest CLI๋ฅผ ์ „์—ญ์œผ๋กœ ์„ค์น˜ํ•˜๊ฑฐ๋‚˜, npx๋กœ ๋ฐ”๋กœ ์Šค์บํด๋”ฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค:

# ์˜ต์…˜ A: Nest CLI ์ „์—ญ ์„ค์น˜ (๊ถŒ์žฅ)
npm install -g @nestjs/cli
nest --version

# ์ƒˆ ํ”„๋กœ์ ํŠธ ์Šค์บํด๋”ฉ ์ƒ์„ฑ (ํŒจํ‚ค์ง€ ๋งค๋‹ˆ์ €๋Š” npm/pnpm/yarn ์ค‘ ์„ ํƒ)
nest new my-nest-app --package-manager npm
cd my-nest-app

# ์˜ต์…˜ B: CLI ์ „์—ญ ์„ค์น˜ ์—†์ด npx๋กœ ์ฆ‰์‹œ ์ƒ์„ฑ
npx @nestjs/cli new my-nest-app --package-manager npm
cd my-nest-app

โš™๏ธ 3. ํ•„์ˆ˜ TypeScript ์ปดํŒŒ์ผ๋Ÿฌ ์„ค์ • (tsconfig.json)

NestJS๋Š” ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ(@Controller, @Injectable ๋“ฑ)์™€ ๋ฆฌํ”Œ๋ ‰์…˜ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ๋ฅผ ํ•ต์‹ฌ์œผ๋กœ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ, tsconfig.json์— ๋‹ค์Œ ์˜ต์…˜์ด ๋ฐ˜๋“œ์‹œ ํ™œ์„ฑํ™”๋˜์–ด ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ES2021",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

๐Ÿ“ฆ 4. ํ•„์ˆ˜ ์˜์กด์„ฑ ํŒจํ‚ค์ง€ ์„ค์น˜

๊ฒ€์ฆ ํŒŒ์ดํ”„ ๋ฐ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ด€๋ฆฌ์— ํ•„์ˆ˜์ ์ธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์„ค์น˜ํ•ฉ๋‹ˆ๋‹ค:

# DTO ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ๋ฐ ๊ฐ์ฒด ๋ณ€ํ™˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
npm install class-validator class-transformer

# ํ™˜๊ฒฝ๋ณ€์ˆ˜(.env) ์„ค์ • ๋ชจ๋“ˆ
npm install @nestjs/config

# ๊ฐœ๋ฐœ ์„œ๋ฒ„ ์‹คํ–‰ (์ฝ”๋“œ ๋ณ€๊ฒฝ ์‹œ ์ž๋™ ํ•ซ ๋ฆฌ๋กœ๋“œ)
npm run start:dev

2. NestJS ํ•ต์‹ฌ ๊ฐœ๋… & ์š”์ฒญ ์ฒ˜๋ฆฌ ์ƒ๋ช…์ฃผ๊ธฐ (Mental Model)

NestJS๋กœ ๋“ค์–ด์˜ค๋Š” ๋ชจ๋“  HTTP ์š”์ฒญ์€ ์ผ๊ด€๋˜๊ณ  ์ฒด๊ณ„์ ์ธ ํŒŒ์ดํ”„๋ผ์ธ ๋‹จ๊ณ„๋ฅผ ๊ฑฐ์ณ ์ฒ˜๋ฆฌ๋ฉ๋‹ˆ๋‹ค.

๐Ÿ”„ HTTP ์š”์ฒญ ์ฒ˜๋ฆฌ ์ƒ๋ช…์ฃผ๊ธฐ (Request Lifecycle)

[HTTP ํด๋ผ์ด์–ธํŠธ ์š”์ฒญ]
        โ”‚
        โ–ผ
 1. Middleware (๋กœ๊น…, ์„ธ์…˜, CORS, Body ํŒŒ์‹ฑ ๋“ฑ ์ „์—ญ/๋ผ์šฐํŠธ ๋ฏธ๋“ค์›จ์–ด)
        โ”‚
        โ–ผ
 2. Guards (์ธ์ฆ ํ† ํฐ ๊ฒ€์ฆ, Role/๊ถŒํ•œ ์ธ๊ฐ€ ์ฒดํฌ: canActivate())
        โ”‚
        โ–ผ
 3. Interceptors (Pre-Controller: ํ•ธ๋“ค๋Ÿฌ ์ง„์ž… ์ „ ์‹œ๊ฐ„ ์ธก์ •, ์š”์ฒญ ๋ณ€ํ˜•)
        โ”‚
        โ–ผ
 4. Pipes (DTO ์Šคํ‚ค๋งˆ ๊ฒ€์ฆ: class-validator, ํƒ€์ž… ํ˜•๋ณ€ํ™˜: ParseIntPipe)
        โ”‚
        โ–ผ
 5. Controller (ํ•ธ๋“ค๋Ÿฌ ํ•จ์ˆ˜ ๋ผ์šฐํŒ…: @Get, @Post, ์š”์ฒญ ๊ฐ์ฒด ์ถ”์ถœ)
        โ”‚
        โ–ผ
 6. Service / Provider (๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ์—ฐ์‚ฐ, DB ์ฟผ๋ฆฌ, ์™ธ๋ถ€ API ํ˜ธ์ถœ)
        โ”‚
        โ–ผ
 7. Interceptors (Post-Controller: RxJS pipe๋กœ ์‘๋‹ต ๊ตฌ์กฐ ํ‘œ์ค€ํ™”, ์บ์‹ฑ)
        โ”‚
        โ–ผ
 8. Exception Filters (์ฒ˜๋ฆฌ ์ค‘ ๋ฐœ์ƒํ•œ ์˜ˆ์™ธ๋ฅผ ์ผ๊ด€๋œ JSON ์—๋Ÿฌ ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜)
        โ”‚
        โ–ผ
[ํด๋ผ์ด์–ธํŠธ๋กœ HTTP ์‘๋‹ต ์ „์†ก]

๐Ÿงฉ 3๋Œ€ ํ•ต์‹ฌ ์•„ํ‚คํ…์ฒ˜ ๊ตฌ์„ฑ์š”์†Œ

  1. Modules (@Module): ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ตฌ์กฐ๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ๊ฒฝ๊ณ„ ๋‹จ์œ„. Controller์™€ Provider๋ฅผ ๋ฌถ๊ณ , ๋‹ค๋ฅธ ๋ชจ๋“ˆ๊ณผ ๊ฒฐํ•ฉํ•ฉ๋‹ˆ๋‹ค.
  2. Controllers (@Controller): ๋“ค์–ด์˜ค๋Š” ํด๋ผ์ด์–ธํŠธ HTTP ์š”์ฒญ์„ ์ˆ˜์‹ ํ•˜๊ณ , ๊ฒฝ๋กœ ๋งคํ•‘ ํ›„ ์ ์ ˆํ•œ Service๋กœ ์œ„์ž„ํ•ฉ๋‹ˆ๋‹ค.
  3. Providers / Services (@Injectable): ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•˜๋ฉฐ, NestJS IoC(์ œ์–ด์˜ ์—ญ์ „) ์ปจํ…Œ์ด๋„ˆ์— ์˜ํ•ด ์ž๋™์œผ๋กœ ์ƒ์„ฑ์ž ์ฃผ์ž…(DI)๋ฉ๋‹ˆ๋‹ค.

3. [์ดˆ๋ณด์ž 1๋‹จ๊ณ„] ํ—ฌ๋กœ์›”๋“œ: ์ตœ์†Œ ๋™์ž‘ ์˜ˆ์ œ

Nest CLI์˜ ๋ณต์žกํ•œ ๋ณด์ผ๋Ÿฌํ”Œ๋ ˆ์ดํŠธ ์—†์ด, ๋‹จ์ผ ํŒŒ์ผ ์ˆ˜์ค€์˜ ์ตœ์†Œ ์ฝ”๋“œ๋กœ NestJS์˜ ๊ตฌ๋™ ์›๋ฆฌ๋ฅผ ์ฆ‰์‹œ ํŒŒ์•…ํ•  ์ˆ˜ ์žˆ๋Š” ์˜ˆ์ œ์ž…๋‹ˆ๋‹ค.

๐Ÿ“„ ํŒŒ์ผ ์ž‘์„ฑ: src/main-standalone.ts

import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get, Param, ParseIntPipe } from '@nestjs/common';

// 1. Controller ์ •์˜: HTTP ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํ•ธ๋“ค๋Ÿฌ
@Controller('api')
class HelloController {
  @Get('hello')
  getHello(): { message: string; timestamp: string } {
    return {
      message: 'Hello, NestJS World!',
      timestamp: new Date().toISOString(),
    };
  }

  @Get('users/:id')
  getUser(@Param('id', ParseIntPipe) id: number): { userId: number; status: string } {
    return {
      userId: id,
      status: 'active',
    };
  }
}

// 2. Module ์ •์˜: ์ปจํŠธ๋กค๋Ÿฌ์™€ ์˜์กด์„ฑ ํ”„๋กœ๋ฐ”์ด๋”๋ฅผ ๋ฌถ๋Š” ์ปจํ…Œ์ด๋„ˆ
@Module({
  controllers: [HelloController],
})
class HelloAppModule {}

// 3. ๋ถ€ํŠธ์ŠคํŠธ๋žฉ ํ•จ์ˆ˜: Nest ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ๋ฐ ํฌํŠธ ๋ฆฌ์Šค๋‹
async function bootstrap(): Promise<void> {
  const app = await NestFactory.create(HelloAppModule);
  const PORT = 3000;
  await app.listen(PORT);
  console.log(`๐Ÿš€ NestJS ์„œ๋ฒ„๊ฐ€ ๊ตฌ๋™๋˜์—ˆ์Šต๋‹ˆ๋‹ค: http://localhost:${PORT}/api/hello`);
}

bootstrap();

๐Ÿ’ป ์‹คํ–‰ ๋ฐ ๋™์ž‘ ํ™•์ธ

# ts-node๋กœ ์ง์ ‘ ์‹คํ–‰
npx ts-node src/main-standalone.ts

# ์ฝ˜์†” ์ถœ๋ ฅ ํ™•์ธ:
# ๐Ÿš€ NestJS ์„œ๋ฒ„๊ฐ€ ๊ตฌ๋™๋˜์—ˆ์Šต๋‹ˆ๋‹ค: http://localhost:3000/api/hello

# ๋‹ค๋ฅธ ํ„ฐ๋ฏธ๋„์—์„œ curl ์š”์ฒญ ํ…Œ์ŠคํŠธ:
curl http://localhost:3000/api/hello
# ์‘๋‹ต ๊ฒฐ๊ณผ:
# {"message":"Hello, NestJS World!","timestamp":"2026-10-08T11:55:00.000Z"}

curl http://localhost:3000/api/users/42
# ์‘๋‹ต ๊ฒฐ๊ณผ:
# {"userId":42,"status":"active"}

4. [์ดˆ๋ณด์ž 2๋‹จ๊ณ„] ํ•ต์‹ฌ ๊ธฐ๋Šฅ & ๋ชจ๋“ˆ ์•„ํ‚คํ…์ฒ˜

์‹ค๋ฌด NestJS ํ”„๋กœ์ ํŠธ์˜ ๊ธฐ๋ณธ ํ‘œ์ค€์ธ ์ปจํŠธ๋กค๋Ÿฌ, ์„œ๋น„์Šค, DTO ๊ฒ€์ฆ ํŒŒ์ดํ”„ ๋ฐ ๋ชจ๋“ˆ ์‹œ์Šคํ…œ ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค.

๐Ÿ•น๏ธ 1. DTO & Validation Pipe (์ž…๋ ฅ๊ฐ’ ์œ ํšจ์„ฑ ๊ฒ€์ฆ)

ํด๋ผ์ด์–ธํŠธ์˜ ์š”์ฒญ ๋ฐ”๋””(Body)๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ฒ€์ฆํ•˜๋Š” DTO(Data Transfer Object) ํด๋ž˜์Šค์ž…๋‹ˆ๋‹ค.

// src/posts/dto/create-post.dto.ts
import { IsString, IsNotEmpty, MinLength, MaxLength, IsOptional, IsBoolean } from 'class-validator';

export class CreatePostDto {
  @IsString({ message: '์ œ๋ชฉ์€ ๋ฌธ์ž์—ด์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.' })
  @IsNotEmpty({ message: '์ œ๋ชฉ์€ ํ•„์ˆ˜ ์ž…๋ ฅ ํ•ญ๋ชฉ์ž…๋‹ˆ๋‹ค.' })
  @MinLength(2, { message: '์ œ๋ชฉ์€ ์ตœ์†Œ 2์ž ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.' })
  @MaxLength(100, { message: '์ œ๋ชฉ์€ ์ตœ๋Œ€ 100์ž๊นŒ์ง€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.' })
  readonly title: string;

  @IsString({ message: '๋‚ด์šฉ์€ ๋ฌธ์ž์—ด์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.' })
  @IsNotEmpty({ message: '๋‚ด์šฉ์€ ํ•„์ˆ˜ ์ž…๋ ฅ ํ•ญ๋ชฉ์ž…๋‹ˆ๋‹ค.' })
  readonly content: string;

  @IsBoolean()
  @IsOptional()
  readonly isPublished?: boolean = false;
}

โš™๏ธ 2. Service & ์˜์กด์„ฑ ์ฃผ์ž… (Dependency Injection)

@Injectable() ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๊ฐ€ ๋ถ™์€ ํด๋ž˜์Šค๋Š” Nest IoC ์ปจํ…Œ์ด๋„ˆ๊ฐ€ ์ธ์Šคํ„ด์Šค ์ƒ๋ช…์ฃผ๊ธฐ(์‹ฑ๊ธ€ํ†ค ๊ธฐ๋ณธ๊ฐ’)๋ฅผ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

// src/posts/posts.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreatePostDto } from './dto/create-post.dto';

export interface PostItem {
  id: number;
  title: string;
  content: string;
  isPublished: boolean;
  createdAt: Date;
}

@Injectable()
export class PostsService {
  private posts: PostItem[] = [
    {
      id: 1,
      title: 'NestJS ์‹œ์ž‘ํ•˜๊ธฐ',
      content: 'NestJS ์•„ํ‚คํ…์ฒ˜์™€ DI ์‹œ์Šคํ…œ ์ตํžˆ๊ธฐ',
      isPublished: true,
      createdAt: new Date(),
    },
  ];
  private idCounter = 2;

  findAll(): PostItem[] {
    return this.posts;
  }

  findOne(id: number): PostItem {
    const post = this.posts.find((p) => p.id === id);
    if (!post) {
      throw new NotFoundException(`ID๊ฐ€ ${id}์ธ ๊ฒŒ์‹œ๊ธ€์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.`);
    }
    return post;
  }

  create(dto: CreatePostDto): PostItem {
    const newPost: PostItem = {
      id: this.idCounter++,
      title: dto.title,
      content: dto.content,
      isPublished: dto.isPublished ?? false,
      createdAt: new Date(),
    };
    this.posts.push(newPost);
    return newPost;
  }

  remove(id: number): { success: boolean; deletedId: number } {
    this.findOne(id); // ์—†์œผ๋ฉด NotFoundException ๋ฐœ์ƒ
    this.posts = this.posts.filter((p) => p.id !== id);
    return { success: true, deletedId: id };
  }
}

๐ŸŒ 3. Controller & HTTP ๋ผ์šฐํŒ…

๊ฒฝ๋กœ ํŒŒ๋ผ๋ฏธํ„ฐ(@Param), ์ฟผ๋ฆฌ์ŠคํŠธ๋ง(@Query), ๋ณธ๋ฌธ(@Body), ์ƒํƒœ์ฝ”๋“œ(@HttpCode)๋ฅผ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

// src/posts/posts.controller.ts
import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Param,
  ParseIntPipe,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { PostsService, PostItem } from './posts.service';
import { CreatePostDto } from './dto/create-post.dto';

@Controller('posts')
export class PostsController {
  // ์ƒ์„ฑ์ž ์ฃผ์ž…(Constructor Injection): IoC ์ปจํ…Œ์ด๋„ˆ๊ฐ€ PostsService ์‹ฑ๊ธ€ํ†ค ์ฃผ์ž…
  constructor(private readonly postsService: PostsService) {}

  @Get()
  getAllPosts(): PostItem[] {
    return this.postsService.findAll();
  }

  @Get(':id')
  getPostById(@Param('id', ParseIntPipe) id: number): PostItem {
    return this.postsService.findOne(id);
  }

  @Post()
  @HttpCode(HttpStatus.CREATED)
  createPost(@Body() dto: CreatePostDto): PostItem {
    return this.postsService.create(dto);
  }

  @Delete(':id')
  deletePost(@Param('id', ParseIntPipe) id: number): { success: boolean; deletedId: number } {
    return this.postsService.remove(id);
  }
}

๐Ÿ“ฆ 4. ๋ชจ๋“ˆ ๋ถ„๋ฆฌ (@Module) ๋ฐ ์ „์—ญ ํŒŒ์ดํ”„ ๋“ฑ๋ก

๊ธฐ๋Šฅ ๋‹จ์œ„ ๋ชจ๋“ˆ๋กœ ๋ถ„๋ฆฌํ•˜๊ณ  AppModule์— ํ†ตํ•ฉํ•ฉ๋‹ˆ๋‹ค.

// src/posts/posts.module.ts
import { Module } from '@nestjs/common';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';

@Module({
  controllers: [PostsController],
  providers: [PostsService],
  exports: [PostsService], // ๋‹ค๋ฅธ ๋ชจ๋“ˆ์—์„œ PostsService๋ฅผ ์ฃผ์ž…๋ฐ›์„ ์ˆ˜ ์žˆ๋„๋ก ๋…ธ์ถœ
})
export class PostsModule {}
// src/app.module.ts
import { Module } from '@nestjs/common';
import { PostsModule } from './posts/posts.module';

@Module({
  imports: [PostsModule],
})
export class AppModule {}
// src/main.ts (์ง„์ž…์ : ์ „์—ญ ValidationPipe ํ™œ์„ฑํ™”)
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';

async function bootstrap(): Promise<void> {
  const app = await NestFactory.create(AppModule);

  // ์ „์—ญ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ํŒŒ์ดํ”„ ๋“ฑ๋ก (๋งค์šฐ ์ค‘์š”)
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,            // DTO์— ์ •์˜๋˜์ง€ ์•Š์€ ์ž„์˜์˜ ์†์„ฑ์€ ์ž๋™ ์ œ๊ฑฐ
      forbidNonWhitelisted: true, // DTO์— ์ •์˜๋˜์ง€ ์•Š์€ ํ•„๋“œ ์ „๋‹ฌ ์‹œ 400 Bad Request ์—๋Ÿฌ ๋ฐ˜ํ™˜
      transform: true,            // ์š”์ฒญ ํŽ˜์ด๋กœ๋“œ๋ฅผ DTO ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค๋กœ ์ž๋™ ๋ณ€ํ™˜
    }),
  );

  await app.listen(3000);
  console.log('Server running on http://localhost:3000');
}
bootstrap();

5. [์ดˆ๋ณด์ž 3๋‹จ๊ณ„] ์‹ค๋ฌด ์‘์šฉ ํŒจํ„ด & ๋ฏธ๋“ค์›จ์–ด ํŒŒ์ดํ”„๋ผ์ธ

์‹ค๋ฌด ํ”„๋กœ๋•์…˜ ํ™˜๊ฒฝ์—์„œ ํ•„์ˆ˜์ ์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š” ์„ค์ • ๋ชจ๋“ˆ, ์˜ˆ์™ธ ํ•„ํ„ฐ, ์ธํ„ฐ์…‰ํ„ฐ, ์ธ์ฆ ๊ฐ€๋“œ, Swagger ๋ฌธ์„œํ™” ํŒจํ„ด์ž…๋‹ˆ๋‹ค.

๐Ÿ”‘ 1. ConfigModule & ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ด€๋ฆฌ (@nestjs/config)

npm install @nestjs/config
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,                         // ๋ชจ๋“  ๋ชจ๋“ˆ์—์„œ ConfigService ์ฃผ์ž… ๊ฐ€๋Šฅ
      envFilePath: `.env.${process.env.NODE_ENV || 'development'}`,
    }),
  ],
})
export class AppModule {}
// ์„œ๋น„์Šค์—์„œ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์‚ฌ์šฉ ์˜ˆ์‹œ
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class DatabaseConfigService {
  constructor(private readonly configService: ConfigService) {}

  get databaseUrl(): string {
    return this.configService.get<string>('DATABASE_URL', 'localhost:5432');
  }
}

๐Ÿ›ก๏ธ 2. ์ „์—ญ ์˜ˆ์™ธ ํ•„ํ„ฐ (HttpExceptionFilter)

๋ฐฑ์—”๋“œ ์ „์ฒด์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์—๋Ÿฌ ์‘๋‹ต ํฌ๋งท์„ ์ผ๊ด€๋œ JSON ์Šคํ‚ค๋งˆ๋กœ ํ‘œ์ค€ํ™”ํ•ฉ๋‹ˆ๋‹ค.

// src/common/filters/http-exception.filter.ts
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : 'Internal server error';

    const errorResponse = {
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      error: typeof message === 'object' ? message : { message },
    };

    this.logger.error(`[${request.method}] ${request.url} - Status: ${status}`);

    response.status(status).json(errorResponse);
  }
}

โฑ๏ธ 3. ๋กœ๊น… & ์‹คํ–‰์‹œ๊ฐ„ ์ธก์ • ์ธํ„ฐ์…‰ํ„ฐ (LoggingInterceptor)

์š”์ฒญ๊ณผ ์‘๋‹ต์˜ ์‹คํ–‰ ์‹œ๊ฐ„์„ RxJS์˜ tap ์—ฐ์‚ฐ์ž๋กœ ๊ณ„์ธกํ•ฉ๋‹ˆ๋‹ค.

// src/common/interceptors/logging.interceptor.ts
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const { method, url } = request;
    const now = Date.now();

    return next.handle().pipe(
      tap(() => {
        const response = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        this.logger.log(`[${method}] ${url} ${response.statusCode} +${delay}ms`);
      }),
    );
  }
}

๐Ÿ” 4. ์ธ์ฆ & ์ธ๊ฐ€ ๊ฐ€๋“œ (Auth Guard)

์š”์ฒญ ํ—ค๋”์˜ Authorization ํ† ํฐ์„ ๊ฒ€์ฆํ•˜์—ฌ ํ•ธ๋“ค๋Ÿฌ ์ ‘๊ทผ์„ ์ œ์–ดํ•ฉ๋‹ˆ๋‹ค.

// src/common/guards/auth.guard.ts
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class SimpleAuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const authHeader = request.headers['authorization'];

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw new UnauthorizedException('์ธ์ฆ ํ† ํฐ์ด ๋ˆ„๋ฝ๋˜์—ˆ๊ฑฐ๋‚˜ ์œ ํšจํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.');
    }

    const token = authHeader.split(' ')[1];
    // ํ† ํฐ ๊ฒ€์ฆ ๋กœ์ง (์‹ค๋ฌด: jwtService.verify(token))
    if (token !== 'secret-lucky-token') {
      throw new UnauthorizedException('์œ ํšจํ•˜์ง€ ์•Š์€ ํ† ํฐ์ž…๋‹ˆ๋‹ค.');
    }

    // ๊ฒ€์ฆ๋œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ request ๊ฐ์ฒด์— ์ฃผ์ž…
    request.user = { userId: 1, username: 'lucky_developer' };
    return true;
  }
}

// ์ปจํŠธ๋กค๋Ÿฌ ์ ์šฉ ์˜ˆ์‹œ:
// @UseGuards(SimpleAuthGuard)
// @Get('protected')
// getProtectedData(@Req() req) { return req.user; }

๐Ÿ“– 5. Swagger (OpenAPI) ๋ฌธ์„œ ์ž๋™ ์ƒ์„ฑ

npm install @nestjs/swagger
// src/main.ts ์—์„œ Swagger ์„ค์ • ๋“ฑ๋ก
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';

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

  const config = new DocumentBuilder()
    .setTitle('LuckyTechWorld API')
    .setDescription('NestJS ๊ณ ์„ฑ๋Šฅ ์—”ํ„ฐํ”„๋ผ์ด์ฆˆ REST API ๋ช…์„ธ์„œ')
    .setVersion('1.0.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api/docs', app, document);

  await app.listen(3000);
  console.log('Swagger UI: http://localhost:3000/api/docs');
}
bootstrap();

6. ์‹ค๋ฌด ์ฃผ์˜์‚ฌํ•ญ & ํ”„๋กœ๋•์…˜ ์ฒดํฌ๋ฆฌ์ŠคํŠธ

โš ๏ธ 1. ์ดˆ๋ณด์ž๊ฐ€ ๊ฐ€์žฅ ํ”ํžˆ ๊ฒช๋Š” ์‹ค์ˆ˜ & ํ•ด๊ฒฐ๋ฒ•

๋ฒˆํ˜ธํ”ํ•œ ์—๋Ÿฌ ๋ฐ ์ฆ์ƒ๊ทผ๋ณธ ์›์ธํ•ด๊ฒฐ ๋ฐฉ๋ฒ•
1Nest can't resolve dependencies of the XService (?)์˜์กดํ•˜๋Š” Service๊ฐ€ ์†ํ•œ ๋ชจ๋“ˆ์—์„œ exportsํ•˜์ง€ ์•Š์•˜๊ฑฐ๋‚˜, ๋Œ€์ƒ ๋ชจ๋“ˆ์˜ imports ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•˜์ง€ ์•Š์Œ๊ณต๊ธ‰์ž ๋ชจ๋“ˆ์˜ @Module({ exports: [XService] }) ํ™•์ธ ํ›„ ์†Œ๋น„์ž ๋ชจ๋“ˆ์˜ imports: [XModule] ์ถ”๊ฐ€
2์ˆœํ™˜ ์ฐธ์กฐ ์—๋Ÿฌ (A โž” B โž” A)๋‘ ๋ชจ๋“ˆ ๋˜๋Š” ์„œ๋น„์Šค๊ฐ€ ์„œ๋กœ๋ฅผ ์ง์ ‘ ์ฃผ์ž…ํ•˜๊ณ  ์žˆ์Œ์ƒ์„ฑ์ž ์ฃผ์ž… ์‹œ @Inject(forwardRef(() => OtherService)) ๋ฐ imports: [forwardRef(() => OtherModule)] ์‚ฌ์šฉ
3DTO ๊ฒ€์ฆ ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๊ฐ€ ์ „ํ˜€ ๋™์ž‘ํ•˜์ง€ ์•Š์Œmain.ts์— app.useGlobalPipes(new ValidationPipe()) ๋ฏธ๋“ฑ๋กmain.ts ๋ถ€ํŠธ์ŠคํŠธ๋žฉ ํ•จ์ˆ˜ ๋‚ด ์ „์—ญ ValidationPipe ์ถ”๊ฐ€
4๋ฐ์ฝ”๋ ˆ์ดํ„ฐ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ์—๋Ÿฌ (Unable to resolve signature...)tsconfig.json ์ปดํŒŒ์ผ๋Ÿฌ ํ”Œ๋ž˜๊ทธ ๋ˆ„๋ฝexperimentalDecorators: true, emitDecoratorMetadata: true ์„ค์ • ํ™•์ธ

๐Ÿš€ 2. ํ”„๋กœ๋•์…˜ ์„ฑ๋Šฅ & ๋ณด์•ˆ ์ฒดํฌ๋ฆฌ์ŠคํŠธ

  1. Fastify ์–ด๋Œ‘ํ„ฐ ์ „ํ™˜ (์ดˆ๊ณ ์† ์„ฑ๋Šฅ ํ•„์š” ์‹œ): ๊ธฐ๋ณธ Express ์–ด๋Œ‘ํ„ฐ ๋Œ€์‹  Fastify๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ดˆ๋‹น ์ฒ˜๋ฆฌ๋Ÿ‰(RPS)์ด ์ตœ๋Œ€ 2๋ฐฐ๊นŒ์ง€ ํ–ฅ์ƒ๋ฉ๋‹ˆ๋‹ค.
    npm install @nestjs/platform-fastify
    import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
    const app = await NestFactory.create<NestFastifyApplication>(
      AppModule,
      new FastifyAdapter(),
    );
  2. ๋ณด์•ˆ ํ—ค๋” & CORS:
    npm install helmet
    import helmet from 'helmet';
    app.use(helmet());
    app.enableCors({ origin: ['https://luckytech.world'], credentials: true });
  3. ๋””๋„์Šค/๋‚จ์šฉ ๋ฐฉ์ง€ Rate Limiting:
    npm install @nestjs/throttler
  4. Graceful Shutdown (์šฐ์•„ํ•œ ์ข…๋ฃŒ ๋ณด์žฅ): Kubernetes ์ปจํ…Œ์ด๋„ˆ ๋กค๋ง ๋ฐฐํฌ ์‹œ ์ง„ํ–‰ ์ค‘์ธ ์š”์ฒญ์˜ ์œ ์‹ค์„ ๋ฐฉ์ง€ํ•ฉ๋‹ˆ๋‹ค:
    // main.ts
    app.enableShutdownHooks();

โšก 3. Nest CLI ํ•ต์‹ฌ ๋‹จ์ถ• ๋ช…๋ น์–ด ๋ชจ์Œ

์ž‘์—… ๋ชฉ์ ์ „์ฒด ๋ช…๋ น์–ด๋‹จ์ถ• ๋ช…๋ น์–ด์ž๋™ ์ƒ์„ฑ ๊ฒฐ๊ณผ๋ฌผ
ํ”„๋กœ์ ํŠธ ์ƒ์„ฑnest new <์ด๋ฆ„>nest new <์ด๋ฆ„>์ „์ฒด ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ ์Šค์บํด๋”ฉ
CRUD ์ „์ฒด ๋ฆฌ์†Œ์Šคnest generate resource <์ด๋ฆ„>nest g res <์ด๋ฆ„>Controller + Service + Module + DTO + Entity ์ผ๊ด„ ์ƒ์„ฑ
๋ชจ๋“ˆ ์ƒ์„ฑnest generate module <์ด๋ฆ„>nest g mo <์ด๋ฆ„>xxx.module.ts ์ƒ์„ฑ ๋ฐ AppModule ๋“ฑ๋ก
์ปจํŠธ๋กค๋Ÿฌ ์ƒ์„ฑnest generate controller <์ด๋ฆ„>nest g co <์ด๋ฆ„>xxx.controller.ts ์ƒ์„ฑ ๋ฐ Module ๋“ฑ๋ก
์„œ๋น„์Šค ์ƒ์„ฑnest generate service <์ด๋ฆ„>nest g s <์ด๋ฆ„>xxx.service.ts ์ƒ์„ฑ ๋ฐ Module ๋“ฑ๋ก
๊ฐ€๋“œ ์ƒ์„ฑnest generate guard <์ด๋ฆ„>nest g gu <์ด๋ฆ„>xxx.guard.ts ์ƒ์„ฑ
์ธํ„ฐ์…‰ํ„ฐ ์ƒ์„ฑnest generate interceptor <์ด๋ฆ„>nest g in <์ด๋ฆ„>xxx.interceptor.ts ์ƒ์„ฑ
์˜ˆ์™ธ ํ•„ํ„ฐ ์ƒ์„ฑnest generate filter <์ด๋ฆ„>nest g f <์ด๋ฆ„>xxx.filter.ts ์ƒ์„ฑ
๋ฏธ๋“ค์›จ์–ด ์ƒ์„ฑnest generate middleware <์ด๋ฆ„>nest g mi <์ด๋ฆ„>xxx.middleware.ts ์ƒ์„ฑ
๐Ÿ’ฌ

์˜๊ฒฌ ๋ฐ ์งˆ๋ฌธ

0
0 / 1500