โšก

Fastify & TypeProvider ์น˜ํŠธ์‹œํŠธ

Node.js ์ดˆ๊ณ ์† ์›น ํ”„๋ ˆ์ž„์›Œํฌ ์™„๋ฒฝ ๊ฐ€์ด๋“œ: ์‹œ์Šคํ…œ ์š”๊ตฌ์‚ฌ์–‘, TypeBox/Zod ๊ธฐ๋ฐ˜ TypeProvider ํƒ€์ž… ์•ˆ์ „ ๋ผ์šฐํŒ…, Ajv ์Šคํ‚ค๋งˆ ๊ฒ€์ฆ ๋ฐ ๊ณ ์„ฑ๋Šฅ ์ง๋ ฌํ™”, ํ”Œ๋Ÿฌ๊ทธ์ธ ์บก์Аํ™” ์•„ํ‚คํ…์ฒ˜, Swagger ์ž๋™ ๋ฌธ์„œํ™”, Pino ๋กœ๊น… ๋ฐ ํ”„๋กœ๋•์…˜ ๋ฐฐํฌ

--views
๋‹จ์ˆ˜:
#fastify#typeprovider#typescript#typebox#zod#nodejs#rest-api#ajv#swagger#openapi์ตœ์ข… ์—…๋ฐ์ดํŠธ: 2026-10-31

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

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

ํ•ญ๋ชฉ์ตœ์†Œ ์‚ฌ์–‘ (Minimum)๊ถŒ์žฅ ์‚ฌ์–‘ (Recommended)์ฐธ๊ณ  ๋ฐ ๋น„๊ณ 
์šด์˜์ฒด์ œ (OS)Linux, macOS, Windows 10/11Ubuntu 22.04 LTS / Debian 12, macOS (Apple Silicon)์ปจํ…Œ์ด๋„ˆ(Docker/K8s) ๋ฐฐํฌ์— ์ตœ์ ํ™”
CPU1 ์ฝ”์–ด (x86_64 ๋˜๋Š” ARM64)2 ์ฝ”์–ด ~ 4 ์ฝ”์–ด ์ด์ƒV8 JIT ์ตœ์ ํ™” ๋ฐ Ajv ์Šคํ‚ค๋งˆ ์ปดํŒŒ์ผ
๋ฉ”๋ชจ๋ฆฌ (RAM)512 MB ์ด์ƒ2 GB ~ 4 GB ์ด์ƒํ”„๋กœ๋•์…˜ Pino ๋ฒ„ํผ๋ง ๋ฐ ๊ณ ์„ฑ๋Šฅ ์ฒ˜๋ฆฌ ๊ถŒ์žฅ
๋””์Šคํฌ (Storage)300 MB ์ด์ƒ์˜ ์—ฌ์œ  ๊ณต๊ฐ„2 GB ์ด์ƒ์˜ ๊ณ ์† SSDnode_modules ๋ฐ TypeScript ๋นŒ๋“œ ์‚ฐ์ถœ๋ฌผ
๋„คํŠธ์›Œํฌ / ๋Ÿฐํƒ€์ž„Node.js 18.x LTS (๊ถŒ์žฅ: 20.x+)Node.js 22 LTS ๋˜๋Š” 20 LTS (Active)TypeScript 5.4+ ํ™˜๊ฒฝ ๊ถŒ์žฅ

Fastify(ํŒจ์Šคํ‹ฐํŒŒ์ด)๋Š” Node.js ์ƒํƒœ๊ณ„์—์„œ ๊ฐ€์žฅ ๋‚ฎ์€ ์˜ค๋ฒ„ํ—ค๋“œ์™€ ๊ทนํ•œ์˜ ์ฒ˜๋ฆฌ๋Ÿ‰(Throughput)์„ ์ œ๊ณตํ•˜๋„๋ก ์„ค๊ณ„๋œ ์›น ํ”„๋ ˆ์ž„์›Œํฌ์ž…๋‹ˆ๋‹ค. Express ๋Œ€๋น„ ์ตœ๋Œ€ 4~5๋ฐฐ ๋†’์€ ์ดˆ๋‹น ์š”์ฒญ ์ฒ˜๋ฆฌ(RPS) ์„ฑ๋Šฅ์„ ๋ณด์ด๋ฉฐ, Ajv ๊ธฐ๋ฐ˜ JSON ์Šคํ‚ค๋งˆ ์œ ํšจ์„ฑ ๊ฒ€์ฆ, fast-json-stringify ๊ธฐ๋ฐ˜ ์ดˆ๊ณ ์† JSON ์ง๋ ฌํ™”, ๊ทธ๋ฆฌ๊ณ  TypeProvider๋ฅผ ํ†ตํ•œ ์ปดํŒŒ์ผ ํƒ€์ž„ ์—”๋“œํˆฌ์—”๋“œ ์ •์  ํƒ€์ž… ์ถ”๋ก ์„ ๋„ค์ดํ‹ฐ๋ธŒ๋กœ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค.


๐ŸŸข 1. Node.js ๋Ÿฐํƒ€์ž„ ๋ฐ ํŒจํ‚ค์ง€ ๋งค๋‹ˆ์ € ์ค€๋น„

# 1. Node.js LTS ๋ฒ„์ „ ํ™•์ธ (20.x ์ด์ƒ ๊ถŒ์žฅ)
node -v
npm -v

# 2. ์ตœ์‹  pnpm ๋˜๋Š” npm ์ตœ์‹ ํ™” (pnpm ์‚ฌ์šฉ ๊ถŒ์žฅ)
npm install -g pnpm
pnpm -v

๐Ÿ› ๏ธ 2. TypeScript ํ”„๋กœ์ ํŠธ ์ดˆ๊ธฐํ™” ๋ฐ ํ•ต์‹ฌ ์˜์กด์„ฑ ์„ค์น˜

Fastify์™€ TypeBox ๊ธฐ๋ฐ˜ TypeProvider ํ™˜๊ฒฝ์„ ๊ตฌ์ถ•ํ•ฉ๋‹ˆ๋‹ค:

# 1. ํ”„๋กœ์ ํŠธ ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™”
mkdir fastify-api-server && cd fastify-api-server
pnpm init

# 2. Fastify ํ•ต์‹ฌ ๋Ÿฐํƒ€์ž„ ๋ฐ TypeProvider ํŒจํ‚ค์ง€ ์„ค์น˜
pnpm add fastify @fastify/type-provider-typebox @sinclair/typebox

# 3. ๊ฐœ๋ฐœ ํŽธ์˜ ๋ฐ ์‹ค๋ฌด ํ”Œ๋Ÿฌ๊ทธ์ธ ์„ค์น˜ (Swagger, CORS, Sensible ๋“ฑ)
pnpm add @fastify/cors @fastify/helmet @fastify/swagger @fastify/swagger-ui @fastify/sensible fastify-plugin

# 4. TypeScript ๋ฐ ์‹คํ–‰ ๋„๊ตฌ ๊ฐœ๋ฐœ ์˜์กด์„ฑ(devDependencies) ์„ค์น˜
pnpm add -D typescript @types/node tsx

โš™๏ธ 3. tsconfig.json ๊ตฌ์„ฑ (ํƒ€์ž… ์ถ”๋ก  ํ•„์ˆ˜ ์˜ต์…˜)

Fastify์™€ TypeProvider์˜ ๊ฐ•๋ ฅํ•œ ํƒ€์ž… ์ถ”๋ก ์„ ์™„๋ฒฝํžˆ ํ™œ์šฉํ•˜๋ ค๋ฉด strict: true ๋ฐ ์ ์ ˆํ•œ ๋ชจ๋“ˆ ํ•ด์„ ์„ค์ •์ด ํ•„์ˆ˜์ ์ž…๋‹ˆ๋‹ค:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "lib": ["ES2022"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"]
}

2. Fastify ๋ฉ˜ํƒˆ ๋ชจ๋ธ & ํ•ต์‹ฌ ์•„ํ‚คํ…์ฒ˜ ๋‹ค์ด์–ด๊ทธ๋žจ

Fastify์˜ ๋†€๋ผ์šด ์†๋„์™€ ๊ฒฌ๊ณ ํ•จ์€ 3๊ฐ€์ง€ ํ•ต์‹ฌ ์•„ํ‚คํ…์ฒ˜ ๊ธฐ๋‘ฅ์—์„œ ๋น„๋กฏ๋ฉ๋‹ˆ๋‹ค:

  1. ํ”Œ๋Ÿฌ๊ทธ์ธ ์บก์Аํ™” ํŠธ๋ฆฌ (Encapsulation Tree): ๋„ค์ž„์ŠคํŽ˜์ด์Šค์™€ ํ›…์„ ๋ถ€๋ชจ-์ž์‹ ๊ฐ„์— ๊ฒฉ๋ฆฌํ•˜์—ฌ ๊ฑฐ๋Œ€ํ•œ ๋ชจ๋…ธ๋ฆฌ์Šค ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜๋„ ์•ˆ์ „ํ•˜๊ฒŒ ๋ชจ๋“ˆํ™”.
  2. ๋‹จ๋ฐฉํ–ฅ ์š”์ฒญ ์ˆ˜๋ช…์ฃผ๊ธฐ ํ›… (Request Lifecycle Pipeline): ๋‹จ๊ณ„๋ณ„ ๋ช…ํ™•ํ•œ ์ธํ„ฐ์…‰ํ„ฐ ์ œ๊ณต.
  3. TypeProvider & Ajv ์Šคํ‚ค๋งˆ ํŒŒ์ดํ”„๋ผ์ธ: ๋Ÿฐํƒ€์ž„ ์œ ํšจ์„ฑ ๊ฒ€์ฆ๊ณผ ์ปดํŒŒ์ผ ํƒ€์ž„ ํƒ€์ž… ์ถ”๋ก ์˜ ์™„๋ฒฝํ•œ ์œตํ•ฉ.

๐Ÿ“ Fastify ์š”์ฒญ ์ˆ˜๋ช…์ฃผ๊ธฐ ๋ฐ TypeProvider ํŒŒ์ดํ”„๋ผ์ธ

[ํด๋ผ์ด์–ธํŠธ HTTP Request ์ „์†ก]
         โ”‚
         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                        Fastify Request Lifecycle                       โ”‚
โ”‚                                                                        โ”‚
โ”‚  1. onRequest โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> ์ „์—ญ ๋กœ๊น…, IP ์ฐจ๋‹จ, ์›์‹œ ์š”์ฒญ ์ธก์ •        โ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  2. preParsing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> ์••์ถ• ํ•ด์ œ, ์›์‹œ ์ŠคํŠธ๋ฆผ ์ „์ฒ˜๋ฆฌ              โ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  3. Parsing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> application/json ๋“ฑ Body ํŒŒ์‹ฑ             โ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  4. preValidation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> [Ajv Schema Validation]                   โ”‚
โ”‚         โ”‚                   โ€ข TypeBox/Zod ์Šคํ‚ค๋งˆ๋กœ Query/Param/Body ๊ฒ€์ฆโ”‚
โ”‚         โ”‚                   โ€ข ์œ ํšจ์„ฑ ๊ฒ€์ฆ ์‹คํŒจ ์‹œ ์ฆ‰์‹œ 400 Bad Requestโ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  5. preHandler โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> ์ธ์ฆ(JWT), ๊ถŒํ•œ ์ธ๊ฐ€(RBAC) ๊ฐ€๋“œ ์ˆ˜ํ–‰        โ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  6. Route Handler โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> [ํƒ€์ž… ์•ˆ์ „ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ์‹คํ–‰]            โ”‚
โ”‚         โ”‚                   โ€ข request.body (์ž๋™ ํƒ€์ž… ์ถ”๋ก  ์™„์„ฑ)       โ”‚
โ”‚         โ”‚                   โ€ข request.query (์ž๋™ ํƒ€์ž… ์ถ”๋ก  ์™„์„ฑ)      โ”‚
โ”‚         โ–ผ                                                              โ”‚
โ”‚  7. preSerialization โ”€โ”€โ”€โ”€โ”€> [fast-json-stringify ์ง๋ ฌํ™”]              โ”‚
โ”‚         โ”‚                   โ€ข ์‘๋‹ต ์Šคํ‚ค๋งˆ ๊ธฐ๋ฐ˜ ํ•„ํ„ฐ๋ง (๋ฏผ๊ฐ ๋ฐ์ดํ„ฐ ๋ฐฉ์ง€)โ”‚
โ”‚         โ”‚                   โ€ข JSON.stringify ๋Œ€๋น„ 2๋ฐฐ ๋น ๋ฅธ C-์Šคํƒ€์ผ ์ถœ๋ ฅโ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  8. onSend โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> ์ตœ์ข… ํ—ค๋”(CORS, Helmet) ๋ฐ ๋ณธ๋ฌธ ๋ณ€์กฐ       โ”‚
โ”‚         โ”‚                                                              โ”‚
โ”‚  9. onResponse โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€> ์‘๋‹ต ์™„๋ฃŒ ํ›„ ๋ฉ”ํŠธ๋ฆญ ๊ธฐ๋ก ๋ฐ ๋กœ๊น…            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚
         โ–ผ
[ํด๋ผ์ด์–ธํŠธ HTTP 200/201 Response ์ˆ˜์‹ ]

๐Ÿงฉ ํ”Œ๋Ÿฌ๊ทธ์ธ ์บก์Аํ™” (Encapsulation) vs fastify-plugin (fp) ๋ชจ๋ธ

[๋ฃจํŠธ Fastify ์ธ์Šคํ„ด์Šค (Root Scope)]
 โ”œโ”€โ”€ [์ผ๋ฐ˜ register] /api/v1 (๋…๋ฆฝ๋œ ์บก์Аํ™” ์Šค์ฝ”ํ”„)
 โ”‚    โ”œโ”€โ”€ ํ›…/๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋Š” ํ•˜์œ„ ์ž์‹์—๊ฒŒ๋งŒ ์ƒ์†๋จ
 โ”‚    โ””โ”€โ”€ ํ˜•์ œ๋‚˜ ๋ถ€๋ชจ ์Šค์ฝ”ํ”„๋ฅผ ์˜ค์—ผ์‹œํ‚ค์ง€ ์•Š์Œ (์™„์ „ ๊ฒฉ๋ฆฌ)
 โ”‚
 โ””โ”€โ”€ [fastify-plugin (fp) register] (๊ณต์œ  ๊ธ€๋กœ๋ฒŒ ์Šค์ฝ”ํ”„)
      โ”œโ”€โ”€ DB ํ’€ (fastify.pg, fastify.prisma)
      โ”œโ”€โ”€ ์ „์—ญ ์ธ์ฆ ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ (fastify.authenticate)
      โ””โ”€โ”€ ์บก์Аํ™” ๋ฒฝ์„ ํ—ˆ๋ฌผ์–ด ๋ถ€๋ชจ ๋ฐ ํ˜•์ œ ๋ผ์šฐํŠธ์— ์ „ํŒŒ

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

Fastify์˜ ๊ณต์‹ ๋นŒํŠธ์ธ ๋กœ๊ฑฐ์ธ Pino๋ฅผ ํ™œ์„ฑํ™”ํ•˜๊ณ , ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋กœ ๊ธฐ๋ณธ GET/POST ์„œ๋ฒ„๋ฅผ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ“ src/server.ts (์ตœ์†Œ ์‹คํ–‰ ๊ฐ€๋Šฅํ•œ ์ „์ฒด ์ฝ”๋“œ)

// src/server.ts
import Fastify, { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

// 1. Fastify ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ (Pino ๋กœ๊ฑฐ ํ™œ์„ฑํ™”)
const app: FastifyInstance = Fastify({
  logger: {
    level: 'info',
    transport: {
      target: 'pino-pretty', // ๊ฐ€๋…์„ฑ ๋†’์€ ์ปฌ๋Ÿฌ ์ฝ˜์†” ์ถœ๋ ฅ (๊ฐœ๋ฐœ์šฉ)
      options: {
        colorize: true,
        translateTime: 'HH:MM:ss Z',
        ignore: 'pid,hostname',
      },
    },
  },
});

// 2. ํ—ฌ์Šค์ฒดํฌ ๋ผ์šฐํŠธ ๋“ฑ๋ก
app.get('/health', async (request: FastifyRequest, reply: FastifyReply) => {
  return {
    status: 'ok',
    uptime: process.uptime(),
    timestamp: new Date().toISOString(),
  };
});

// 3. ๊ฐ„๋‹จํ•œ ํ™˜์˜ ๋ฉ”์‹œ์ง€ ๋ผ์šฐํŠธ (Query ํŒŒ๋ผ๋ฏธํ„ฐ ์ „๋‹ฌ)
app.get('/hello', async (request: FastifyRequest<{ Querystring: { name?: string } }>, reply: FastifyReply) => {
  const name = request.query.name || '๋ฐฉ๋ฌธ์ž';
  return {
    message: `์•ˆ๋…•ํ•˜์„ธ์š”, ${name}๋‹˜! Fastify ์„ธ๊ณ„์— ์˜ค์‹  ๊ฒƒ์„ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค. ๐Ÿš€`,
  };
});

// 4. ์„œ๋ฒ„ ์‹œ์ž‘ ํ•จ์ˆ˜ (Docker ๋ฐฐํฌ๋ฅผ ๊ณ ๋ คํ•˜์—ฌ host: '0.0.0.0' ํ•„์ˆ˜ ์ง€์ •)
const start = async () => {
  try {
    const port = Number(process.env.PORT) || 3000;
    const host = '0.0.0.0';
    
    await app.listen({ port, host });
    app.log.info(`์„œ๋ฒ„๊ฐ€ http://${host}:${port} ์—์„œ ๋Œ€๊ธฐ ์ค‘์ž…๋‹ˆ๋‹ค.`);
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();

๐Ÿ’ป ์‹คํ–‰ ๋ฐ cURL ํ…Œ์ŠคํŠธ

# tsx๋ฅผ ํ†ตํ•ด TypeScript ์ฆ‰์‹œ ์‹คํ–‰
npx tsx src/server.ts

# [ํ…Œ์ŠคํŠธ 1] ํ—ฌ์Šค์ฒดํฌ ํ˜ธ์ถœ
curl -i http://localhost:3000/health

# [์˜ˆ์ƒ ์ถœ๋ ฅ 1]
# HTTP/1.1 200 OK
# content-type: application/json; charset=utf-8
# {"status":"ok","uptime":1.24,"timestamp":"2026-10-31T03:15:00.000Z"}

# [ํ…Œ์ŠคํŠธ 2] ์ฟผ๋ฆฌ์ŠคํŠธ๋ง ์ „๋‹ฌ ํ˜ธ์ถœ
curl -i "http://localhost:3000/hello?name=LuckyTech"

# [์˜ˆ์ƒ ์ถœ๋ ฅ 2]
# HTTP/1.1 200 OK
# {"message":"์•ˆ๋…•ํ•˜์„ธ์š”, LuckyTech๋‹˜! Fastify ์„ธ๊ณ„์— ์˜ค์‹  ๊ฒƒ์„ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค. ๐Ÿš€"}

4. [2๋‹จ๊ณ„] ํ•ต์‹ฌ ๊ธฐ๋Šฅ: TypeProvider & ํƒ€์ž… ์•ˆ์ „ ๋ผ์šฐํŒ…

๊ธฐ์กด Node.js ํ”„๋ ˆ์ž„์›Œํฌ(Express ๋“ฑ)๋Š” TypeScript๋ฅผ ์“ฐ๋”๋ผ๋„ req.body as MyType์ฒ˜๋Ÿผ ๋ถˆ์•ˆ์ „ํ•œ ๋‹จ์–ธ(Type Assertion)์„ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ์Šต๋‹ˆ๋‹ค.
Fastify๋Š” TypeProvider๋ฅผ ๋„์ž…ํ•˜์—ฌ ์Šคํ‚ค๋งˆ(๋Ÿฐํƒ€์ž„ ๊ฒ€์ฆ)๋ฅผ ํ•œ ๋ฒˆ๋งŒ ์ž‘์„ฑํ•˜๋ฉด ์š”์ฒญ ๊ฐ์ฒด(req.body, req.params, req.query)์™€ ์‘๋‹ต ๋ฐ˜ํ™˜ ํƒ€์ž…์ด ์ž๋™์œผ๋กœ 100% ์ถ”๋ก ๋ฉ๋‹ˆ๋‹ค.

๐ŸŒŸ ์˜ต์…˜ A: @sinclair/typebox ๊ธฐ๋ฐ˜ TypeProvider (๊ณต์‹ ๊ฐ•๋ ฅ ์ถ”์ฒœ)

TypeBox๋Š” ํ‘œ์ค€ JSON Schema๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ฐ€์žฅ ๋น ๋ฅด๊ณ  ๊ฐ€๋ฒผ์šด TypeScript ์Šคํ‚ค๋งˆ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ž…๋‹ˆ๋‹ค. Fastify์˜ Ajv ๋ฐ fast-json-stringify์™€ 100% ๋„ค์ดํ‹ฐ๋ธŒ ํ˜ธํ™˜๋ฉ๋‹ˆ๋‹ค.

๐Ÿ“ src/typebox-server.ts (TypeBox ์™„์ „ ๊ตฌ๋™ ์˜ˆ์ œ)

// src/typebox-server.ts
import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type, Static } from '@sinclair/typebox';

// 1. withTypeProvider๋ฅผ ์—ฐ๊ฒฐํ•˜์—ฌ ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ
const app = Fastify({ logger: true }).withTypeProvider<TypeBoxTypeProvider>();

// 2. TypeBox ์Šคํ‚ค๋งˆ ์ •์˜ (๋Ÿฐํƒ€์ž„ ์œ ํšจ์„ฑ ๊ฒ€์ฆ + ์ •์  ํƒ€์ž…)
const CreateUserBodySchema = Type.Object({
  username: Type.String({ minLength: 3, maxLength: 20 }),
  email: Type.String({ format: 'email' }),
  age: Type.Integer({ minimum: 1, maximum: 120 }),
  roles: Type.Array(Type.Union([Type.Literal('admin'), Type.Literal('user')]), { default: ['user'] }),
});

const UserResponseSchema = Type.Object({
  id: Type.String({ format: 'uuid' }),
  username: Type.String(),
  email: Type.String(),
  age: Type.Integer(),
  roles: Type.Array(Type.String()),
  createdAt: Type.String(),
});

const ErrorResponseSchema = Type.Object({
  statusCode: Type.Integer(),
  error: Type.String(),
  message: Type.String(),
});

// ์ •์  ํƒ€์ž… ์ถ”์ถœ (ํ•„์š” ์‹œ ๋น„์ฆˆ๋‹ˆ์Šค ์„œ๋น„์Šค ๊ณ„์ธต์—์„œ ์‚ฌ์šฉ)
export type CreateUserBody = Static<typeof CreateUserBodySchema>;
export type UserResponse = Static<typeof UserResponseSchema>;

// 3. ํƒ€์ž… ์•ˆ์ „ ๋ผ์šฐํŠธ ์„ ์–ธ
app.post(
  '/api/users',
  {
    schema: {
      tags: ['Users'],
      summary: '์‹ ๊ทœ ์‚ฌ์šฉ์ž ๋“ฑ๋ก',
      body: CreateUserBodySchema,
      response: {
        201: UserResponseSchema,
        400: ErrorResponseSchema,
      },
    },
  },
  async (request, reply) => {
    // ๐ŸŽ‰ request.body๋Š” ์ด์ œ CreateUserBody ํƒ€์ž…์œผ๋กœ ์™„๋ฒฝํ•˜๊ฒŒ ์ž๋™ ์ถ”๋ก ๋ฉ๋‹ˆ๋‹ค!
    // ๋ณ„๋„์˜ `as` ์บ์ŠคํŒ…์ด๋‚˜ ๊ฒ€์ฆ ์ฝ”๋“œ ๋ถˆํ•„์š”!
    const { username, email, age, roles } = request.body;

    const newUser: UserResponse = {
      id: '123e4567-e89b-12d3-a456-426614174000',
      username,
      email,
      age,
      roles,
      createdAt: new Date().toISOString(),
    };

    // 201 ์‘๋‹ต ์ฝ”๋“œ๋กœ ์ „์†ก (UserResponseSchema์— ์—†๋Š” ํ•„๋“œ๋Š” ์ž๋™์œผ๋กœ ํ•„ํ„ฐ๋ง ๋ˆ„๋ฝ๋จ)
    return reply.status(201).send(newUser);
  }
);

// 4. ๊ฒฝ๋กœ ํŒŒ๋ผ๋ฏธํ„ฐ(Params) ๋ฐ ์ฟผ๋ฆฌ(Querystring) ๊ฒ€์ฆ ์˜ˆ์ œ
const GetUserParamsSchema = Type.Object({
  userId: Type.String({ minLength: 1 }),
});

const GetUserQuerySchema = Type.Object({
  details: Type.Optional(Type.Boolean()),
});

app.get(
  '/api/users/:userId',
  {
    schema: {
      params: GetUserParamsSchema,
      querystring: GetUserQuerySchema,
      response: {
        200: UserResponseSchema,
      },
    },
  },
  async (request, reply) => {
    const { userId } = request.params; // string ํƒ€์ž… ์ž๋™ ์ถ”๋ก 
    const { details } = request.query;  // boolean | undefined ํƒ€์ž… ์ž๋™ ์ถ”๋ก 

    return {
      id: userId,
      username: 'lucky_developer',
      email: 'dev@luckytech.world',
      age: 28,
      roles: ['admin'],
      createdAt: new Date().toISOString(),
    };
  }
);

const start = async () => {
  await app.listen({ port: 3000, host: '0.0.0.0' });
};
start();

๐Ÿ’ป cURL์„ ํ†ตํ•œ ์œ ํšจ์„ฑ ๊ฒ€์ฆ ํ…Œ์ŠคํŠธ

# 1. ์ •์ƒ ๋“ฑ๋ก ์š”์ฒญ (201 Created)
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"username": "fastify_king", "email": "king@test.com", "age": 25, "roles": ["admin"]}'

# [์ถœ๋ ฅ ๊ฒฐ๊ณผ]
# {"id":"123e4567-e89b-12d3-a456-426614174000","username":"fastify_king","email":"king@test.com","age":25,"roles":["admin"],"createdAt":"2026-10-31T03:20:00.000Z"}

# 2. ๋น„์ •์ƒ ์š”์ฒญ (์ด๋ฉ”์ผ ํฌ๋งท ์˜ค๋ฅ˜ ๋ฐ ๋‚˜์ด 1 ๋ฏธ๋งŒ -> Ajv 400 ์ž๋™ ์ฐจ๋‹จ)
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"username": "ab", "email": "invalid-email", "age": -5}'

# [์ถœ๋ ฅ ๊ฒฐ๊ณผ (Fastify ํ‘œ์ค€ ์—๋Ÿฌ ํ˜•์‹)]
# {
#   "statusCode": 400,
#   "code": "FST_ERR_VALIDATION",
#   "error": "Bad Request",
#   "message": "body/username must NOT have fewer than 3 characters, body/email must match format \"email\", body/age must be >= 1"
# }

๐Ÿ’ก ์˜ต์…˜ B: Zod๋ฅผ ์„ ํ˜ธํ•˜๋Š” ๊ฒฝ์šฐ (@fastify/type-provider-zod)

ํŒ€ ๋‚ด์—์„œ ์ด๋ฏธ Zod๋ฅผ ํ‘œ์ค€์œผ๋กœ ์‚ฌ์šฉ ์ค‘์ธ ๊ฒฝ์šฐ, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ปดํŒŒ์ผ๋Ÿฌ ์„ค์ •์„ ๋งคํ•‘ํ•˜์—ฌ ๋™์ผํ•œ ํƒ€์ž… ์•ˆ์ „์„ฑ์„ ํ™•๋ณดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค:

pnpm add @fastify/type-provider-zod zod
// zod-setup.ts
import Fastify from 'fastify';
import { serializerCompiler, validatorCompiler, ZodTypeProvider } from '@fastify/type-provider-zod';
import { z } from 'zod';

const app = Fastify()
  .setValidatorCompiler(validatorCompiler)
  .setSerializerCompiler(serializerCompiler)
  .withTypeProvider<ZodTypeProvider>();

app.post(
  '/api/login',
  {
    schema: {
      body: z.object({
        account: z.string().min(4),
        password: z.string().min(8),
      }),
      response: {
        200: z.object({
          token: z.string(),
        }),
      },
    },
  },
  async (request, reply) => {
    const { account, password } = request.body; // ์ž๋™ ํƒ€์ž… ์ถ”๋ก 
    return { token: `jwt-token-for-${account}` };
  }
);

5. [3๋‹จ๊ณ„] ์‹ค๋ฌด ์‘์šฉ ํŒจํ„ด: ํ”Œ๋Ÿฌ๊ทธ์ธ ๋ชจ๋“ˆํ™”, Swagger & ๋ณด์•ˆ

Fastify ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ํ”„๋กœ๋•์…˜ ๊ตฌ์กฐ๋Š” ํ”Œ๋Ÿฌ๊ทธ์ธ ์บก์Аํ™”๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ž‘์„ฑ๋ฉ๋‹ˆ๋‹ค.
๋น„์ฆˆ๋‹ˆ์Šค ๋ผ์šฐํŠธ, ๊ณตํ†ต ์œ ํ‹ธ๋ฆฌํ‹ฐ(Swagger, CORS), ์ธ์ฆ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ์™„๋ฒฝํ•˜๊ฒŒ ๋ถ„๋ฆฌํ•˜๋Š” ์‹ค๋ฌด ์•„ํ‚คํ…์ฒ˜์ž…๋‹ˆ๋‹ค.

fastify-api-server/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ plugins/
โ”‚   โ”‚   โ”œโ”€โ”€ swagger.ts       # Swagger / OpenAPI ๋ฌธ์„œํ™” ํ”Œ๋Ÿฌ๊ทธ์ธ
โ”‚   โ”‚   โ””โ”€โ”€ security.ts      # CORS, Helmet, Sensible ํ”Œ๋Ÿฌ๊ทธ์ธ
โ”‚   โ”œโ”€โ”€ routes/
โ”‚   โ”‚   โ””โ”€โ”€ items.ts         # ์•„์ดํ…œ ๊ด€๋ จ CRUD ๋น„์ฆˆ๋‹ˆ์Šค ๋ผ์šฐํŠธ
โ”‚   โ””โ”€โ”€ app.ts               # ํ”Œ๋Ÿฌ๊ทธ์ธ ๊ฒฐํ•ฉ ๋ฐ ์„œ๋ฒ„ ์ธ์Šคํ„ด์Šค ์—”ํŠธ๋ฆฌ
โ””โ”€โ”€ tsconfig.json

๐Ÿ“ 1) Swagger/OpenAPI ์ž๋™ ๋ฌธ์„œํ™” ํ”Œ๋Ÿฌ๊ทธ์ธ (src/plugins/swagger.ts)

// src/plugins/swagger.ts
import fp from 'fastify-plugin';
import swagger from '@fastify/swagger';
import swaggerUi from '@fastify/swagger-ui';

export default fp(async (fastify) => {
  // 1. OpenAPI ์ŠคํŽ™ ์ œ๋„ˆ๋ ˆ์ดํ„ฐ ๋“ฑ๋ก
  await fastify.register(swagger, {
    openapi: {
      info: {
        title: 'LuckyTechWorld Fastify Core API',
        description: 'TypeProvider ๊ธฐ๋ฐ˜์˜ ์ดˆ๊ณ ์† ํƒ€์ž… ์„ธ์ดํ”„ RESTful API ๋ช…์„ธ์„œ',
        version: '1.0.0',
      },
      servers: [
        {
          url: 'http://localhost:3000',
          description: '๋กœ์ปฌ ๊ฐœ๋ฐœ ์„œ๋ฒ„',
        },
      ],
      tags: [
        { name: 'Items', description: '์•„์ดํ…œ ๊ด€๋ฆฌ API' },
        { name: 'Health', description: '์‹œ์Šคํ…œ ์ƒํƒœ ์ ๊ฒ€' },
      ],
    },
  });

  // 2. Swagger UI ์›น ์ฝ˜์†” ๋“ฑ๋ก (/docs)
  await fastify.register(swaggerUi, {
    routePrefix: '/docs',
    uiConfig: {
      docExpansion: 'list',
      deepLinking: false,
    },
  });

  fastify.log.info('Swagger UI๊ฐ€ /docs ์—”๋“œํฌ์ธํŠธ์— ์„ฑ๊ณต์ ์œผ๋กœ ๋งˆ์šดํŠธ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.');
});

๐Ÿ“ 2) ๋ณด์•ˆ ๋ฐ ์ „์—ญ ํ”Œ๋Ÿฌ๊ทธ์ธ (src/plugins/security.ts)

// src/plugins/security.ts
import fp from 'fastify-plugin';
import helmet from '@fastify/helmet';
import cors from '@fastify/cors';
import sensible from '@fastify/sensible';

export default fp(async (fastify) => {
  // 1. HTTP ๋ณด์•ˆ ํ—ค๋” ์ž๋™ ์ฃผ์ž…
  await fastify.register(helmet, {
    contentSecurityPolicy: false, // Swagger UI ์ถฉ๋Œ ๋ฐฉ์ง€์šฉ ์„ค์ •
  });

  // 2. Cross-Origin Resource Sharing (CORS) ๊ตฌ์„ฑ
  await fastify.register(cors, {
    origin: (origin, cb) => {
      // ๋กœ์ปฌ ๊ฐœ๋ฐœ ๋ฐ ์‹ ๋ขฐํ•  ์ˆ˜ ์žˆ๋Š” ๋„๋ฉ”์ธ ํ—ˆ์šฉ
      cb(null, true);
    },
    methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
    credentials: true,
  });

  // 3. fastify-sensible: reply.notFound(), reply.badRequest() ๋“ฑ HTTP ์˜ค๋ฅ˜ ํ—ฌํผ ์ œ๊ณต
  await fastify.register(sensible);
});

๐Ÿ“ 3) ๋น„์ฆˆ๋‹ˆ์Šค ๋ผ์šฐํŠธ ๋ชจ๋“ˆํ™” (src/routes/items.ts)

// src/routes/items.ts
import { FastifyPluginAsync } from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';

// ๋ฉ”๋ชจ๋ฆฌ DB ๋ชจ์˜ ๋ฐ์ดํ„ฐ
interface Item {
  id: number;
  name: string;
  price: number;
  stock: number;
}
const itemsDb: Item[] = [
  { id: 1, name: '๋งฅ๋ถ ํ”„๋กœ M3', price: 2900000, stock: 15 },
  { id: 2, name: '๊ธฐ๊ณ„์‹ ํ‚ค๋ณด๋“œ', price: 180000, stock: 50 },
];

const ItemSchema = Type.Object({
  id: Type.Integer(),
  name: Type.String(),
  price: Type.Number(),
  stock: Type.Integer(),
});

const CreateItemBody = Type.Object({
  name: Type.String({ minLength: 2 }),
  price: Type.Number({ minimum: 100 }),
  stock: Type.Integer({ minimum: 0, default: 0 }),
});

const itemRoutes: FastifyPluginAsync = async (fastify) => {
  const app = fastify.withTypeProvider<TypeBoxTypeProvider>();

  // [๋ชฉ๋ก ์กฐํšŒ] GET /api/v1/items
  app.get(
    '/',
    {
      schema: {
        tags: ['Items'],
        summary: '์•„์ดํ…œ ์ „์ฒด ๋ชฉ๋ก ์กฐํšŒ',
        response: {
          200: Type.Array(ItemSchema),
        },
      },
    },
    async (request, reply) => {
      return itemsDb;
    }
  );

  // [์‹ ๊ทœ ์ƒ์„ฑ] POST /api/v1/items
  app.post(
    '/',
    {
      schema: {
        tags: ['Items'],
        summary: '์ƒˆ ์•„์ดํ…œ ์ƒ์„ฑ',
        body: CreateItemBody,
        response: {
          201: ItemSchema,
        },
      },
    },
    async (request, reply) => {
      const { name, price, stock } = request.body;
      const newItem: Item = {
        id: itemsDb.length + 1,
        name,
        price,
        stock,
      };
      itemsDb.push(newItem);
      return reply.status(201).send(newItem);
    }
  );

  // [๋‹จ๊ฑด ์กฐํšŒ] GET /api/v1/items/:id
  app.get(
    '/:id',
    {
      schema: {
        tags: ['Items'],
        summary: '์•„์ดํ…œ ์ƒ์„ธ ์กฐํšŒ',
        params: Type.Object({ id: Type.Integer() }),
        response: {
          200: ItemSchema,
          404: Type.Object({ statusCode: Type.Integer(), error: Type.String(), message: Type.String() }),
        },
      },
    },
    async (request, reply) => {
      const { id } = request.params;
      const found = itemsDb.find((item) => item.id === id);

      if (!found) {
        // fastify-sensible์˜ ํŽธ์˜ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
        return reply.notFound(`ID๊ฐ€ ${id}์ธ ์•„์ดํ…œ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.`);
      }

      return found;
    }
  );
};

export default itemRoutes;

๐Ÿ“ 4) ๋ฉ”์ธ ์•ฑ ๊ตฌ์„ฑ ๋ฐ Graceful Shutdown (src/app.ts)

// src/app.ts
import Fastify from 'fastify';
import swaggerPlugin from './plugins/swagger.js';
import securityPlugin from './plugins/security.js';
import itemRoutes from './routes/items.js';

export const buildApp = async () => {
  const app = Fastify({
    logger: {
      level: process.env.LOG_LEVEL || 'info',
    },
  });

  // 1. ๊ณตํ†ต ํ”Œ๋Ÿฌ๊ทธ์ธ ๋“ฑ๋ก
  await app.register(securityPlugin);
  await app.register(swaggerPlugin);

  // 2. ๋น„์ฆˆ๋‹ˆ์Šค ๋ผ์šฐํŠธ ๋“ฑ๋ก (URL Prefix ์ ์šฉ)
  await app.register(itemRoutes, { prefix: '/api/v1/items' });

  // 3. ์ „์—ญ ์—๋Ÿฌ ํ•ธ๋“ค๋Ÿฌ ์ปค์Šคํ„ฐ๋งˆ์ด์ง•
  app.setErrorHandler((error, request, reply) => {
    app.log.error(error);

    // Ajv ์Šคํ‚ค๋งˆ ๊ฒ€์ฆ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ
    if (error.validation) {
      return reply.status(400).send({
        statusCode: 400,
        error: 'Bad Request',
        message: error.message,
        details: error.validation,
      });
    }

    // ์ผ๋ฐ˜ 500 ์ธํ„ฐ๋„ ์„œ๋ฒ„ ์—๋Ÿฌ
    return reply.status(error.statusCode || 500).send({
      statusCode: error.statusCode || 500,
      error: error.name || 'Internal Server Error',
      message: error.message || '์„œ๋ฒ„ ๋‚ด๋ถ€ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.',
    });
  });

  return app;
};

// ์ง์ ‘ ์‹คํ–‰ ์‹œ ๊ตฌ๋™๋ถ€
const start = async () => {
  const app = await buildApp();
  const port = Number(process.env.PORT) || 3000;
  const host = '0.0.0.0';

  // Graceful Shutdown (SIGINT, SIGTERM)
  const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM'];
  for (const signal of signals) {
    process.on(signal, async () => {
      app.log.info(`[${signal}] ์‹ ํ˜ธ๋ฅผ ์ˆ˜์‹ ํ–ˆ์Šต๋‹ˆ๋‹ค. ์„œ๋ฒ„๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค...`);
      try {
        await app.close();
        app.log.info('๋ชจ๋“  ํ™œ์„ฑ ์ปค๋„ฅ์…˜์ด ์ข…๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ํ”„๋กœ์„ธ์Šค๋ฅผ ์ •์ƒ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.');
        process.exit(0);
      } catch (err) {
        app.log.error(err, '์„œ๋ฒ„ ์ข…๋ฃŒ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ');
        process.exit(1);
      }
    });
  }

  try {
    await app.listen({ port, host });
    console.log(`\n======================================================`);
    console.log(`๐Ÿš€ Fastify ์„œ๋ฒ„ ์ค€๋น„ ์™„๋ฃŒ!`);
    console.log(`๐Ÿ“ก ์—”๋“œํฌ์ธํŠธ: http://localhost:${port}/api/v1/items`);
    console.log(`๐Ÿ“š Swagger UI:  http://localhost:${port}/docs`);
    console.log(`======================================================\n`);
  } catch (err) {
    app.log.error(err);
    process.exit(1);
  }
};

start();

6. ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ & ํ›…(Hooks)์„ ์ด์šฉํ•œ ์ธ์ฆ ๋ฏธ๋“ค์›จ์–ด ํŒจํ„ด

Fastify์—์„œ๋Š” Express ๋ฏธ๋“ค์›จ์–ด ๋Œ€์‹  **๋ฐ์ฝ”๋ ˆ์ดํ„ฐ(decorate)**์™€ preHandler ์ˆ˜๋ช…์ฃผ๊ธฐ ํ›…์„ ์‚ฌ์šฉํ•˜์—ฌ ์‚ฌ์šฉ์ž ์ธ์ฆ ๋ฐ ๊ถŒํ•œ์„ ๊ฒ€์ฆํ•ฉ๋‹ˆ๋‹ค.

// src/plugins/auth.ts
import fp from 'fastify-plugin';
import { FastifyRequest, FastifyReply } from 'fastify';

// 1. Fastify ์ธ์Šคํ„ด์Šค ๋ฐ Request ํƒ€์ž… ํ™•์žฅ (TypeScript ์ธํ„ฐํŽ˜์ด์Šค ๋ณ‘ํ•ฉ)
declare module 'fastify' {
  interface FastifyInstance {
    authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
  }
  interface FastifyRequest {
    user?: {
      id: string;
      role: 'admin' | 'user';
    };
  }
}

export default fp(async (fastify) => {
  // 2. authenticate ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ ํ•จ์ˆ˜ ๋“ฑ๋ก
  fastify.decorate('authenticate', async (request: FastifyRequest, reply: FastifyReply) => {
    const authHeader = request.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return reply.status(401).send({
        statusCode: 401,
        error: 'Unauthorized',
        message: '์œ ํšจํ•œ Bearer ์ธ์ฆ ํ† ํฐ์ด ๋ˆ„๋ฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.',
      });
    }

    const token = authHeader.substring(7);

    // ์‹ค์ œ ํ™˜๊ฒฝ์—์„œ๋Š” jwt.verify() ๋“ฑ์„ ์ˆ˜ํ–‰
    if (token !== 'secret-admin-token') {
      return reply.status(403).send({
        statusCode: 403,
        error: 'Forbidden',
        message: '์ ‘๊ทผ ๊ถŒํ•œ์ด ์—†๋Š” ํ† ํฐ์ž…๋‹ˆ๋‹ค.',
      });
    }

    // ๊ฒ€์ฆ๋œ ์‚ฌ์šฉ์ž ์ •๋ณด๋ฅผ request ๊ฐ์ฒด์— ์ฃผ์ž…
    request.user = { id: 'usr_admin_001', role: 'admin' };
  });
});

๐Ÿ”’ ๋ผ์šฐํŠธ์— ์ธ์ฆ ๊ฐ€๋“œ ์ ์šฉ

// ๋ผ์šฐํŠธ ์ •์˜ ์‹œ preHandler์— fastify.authenticate ์—ฐ๊ฒฐ
app.delete(
  '/api/v1/items/:id',
  {
    preHandler: [fastify.authenticate], // ์ธ์ฆ ๊ฐ€๋“œ ํ†ต๊ณผ ํ›„์—๋งŒ ํ•ธ๋“ค๋Ÿฌ ์‹คํ–‰
    schema: {
      tags: ['Items'],
      summary: '์•„์ดํ…œ ์‚ญ์ œ (๊ด€๋ฆฌ์ž ์ „์šฉ)',
      params: Type.Object({ id: Type.Integer() }),
    },
  },
  async (request, reply) => {
    const { id } = request.params;
    const currentUser = request.user!; // ์ธ์ฆ ๊ฐ€๋“œ๋ฅผ ํ†ต๊ณผํ–ˆ์œผ๋ฏ€๋กœ ์•ˆ์ „ํ•˜๊ฒŒ ์ ‘๊ทผ ๊ฐ€๋Šฅ

    return {
      message: `์•„์ดํ…œ ${id}๋ฒˆ์ด ๊ด€๋ฆฌ์ž(${currentUser.id})์— ์˜ํ•ด ์ •์ƒ ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.`,
    };
  }
);

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

โš ๏ธ 1. ํ”Œ๋Ÿฌ๊ทธ์ธ ์บก์Аํ™” ํ•จ์ • (fastify-plugin ๋ฏธ์‚ฌ์šฉ ์‹ค์ˆ˜)

  • ์ฆ์ƒ: ํ”Œ๋Ÿฌ๊ทธ์ธ ํŒŒ์ผ ์•ˆ์—์„œ fastify.decorate('db', dbClient)๋ฅผ ์‹คํ–‰ํ–ˆ๋Š”๋ฐ, ๋‹ค๋ฅธ ๋ผ์šฐํŠธ ํŒŒ์ผ์—์„œ fastify.db๊ฐ€ undefined๋กœ ์กฐํšŒ๋จ.
  • ์›์ธ: Fastify๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ app.register()๋กœ ๋“ฑ๋ก๋œ ํ”Œ๋Ÿฌ๊ทธ์ธ์„ ์ƒˆ๋กœ์šด ์ž์‹ ์Šค์ฝ”ํ”„๋กœ ์บก์Аํ™”ํ•ฉ๋‹ˆ๋‹ค.
  • ํ•ด๊ฒฐ์ฑ…: ๋ฃจํŠธ ์Šค์ฝ”ํ”„ ์ „์ฒด์—์„œ ๊ณต์œ ํ•ด์•ผ ํ•˜๋Š” ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ, ์œ ํ‹ธ๋ฆฌํ‹ฐ, DB ์ปค๋„ฅ์…˜ ํ’€ ํ”Œ๋Ÿฌ๊ทธ์ธ์€ ๋ฐ˜๋“œ์‹œ **fastify-plugin(fp)**์œผ๋กœ ๋ž˜ํ•‘ํ•˜์—ฌ ๋‚ด๋ณด๋‚ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
import fp from 'fastify-plugin';

export default fp(async (fastify) => {
  fastify.decorate('db', new DatabasePool());
});

โš ๏ธ 2. async ํ•จ์ˆ˜์—์„œ return reply.send() ์ค‘๋ณต ํ˜ธ์ถœ ๊ธˆ์ง€

  • ์ฆ์ƒ: ์ฝ˜์†”์— FST_ERR_REP_ALREADY_SENT: Response was already sent ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•จ.
  • ์›์ธ: async ๋ผ์šฐํŠธ ํ•ธ๋“ค๋Ÿฌ์—์„œ ๊ฐ’์„ returnํ•˜๋ฉด Fastify๊ฐ€ ํ•ด๋‹น ๋ฐ˜ํ™˜๊ฐ’์„ ์ž๋™์œผ๋กœ ์‘๋‹ต์œผ๋กœ ์ „์†กํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ return reply.send(data)๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด reply.send()๋กœ ํ•œ ๋ฒˆ, return์œผ๋กœ ๋˜ ํ•œ ๋ฒˆ ์‘๋‹ต์„ ์‹œ๋„ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
  • ๊ทœ์น™:
    • async ํ•จ์ˆ˜ ๋‚ด์—์„œ๋Š” ์ˆœ์ˆ˜ ๊ฐ์ฒด๋ฅผ ๋ฐ”๋กœ return data ํ•˜๊ฑฐ๋‚˜,
    • ์ƒํƒœ ์ฝ”๋“œ๋ฅผ ์ปค์Šคํ…€ํ•  ๋•Œ๋Š” return reply.status(201).send(data) ํ˜•ํƒœ๋กœ ํ˜ธ์ถœํ•˜์‹ญ์‹œ์˜ค.

โš ๏ธ 3. Docker ๋ฐฐํฌ ์‹œ host: '0.0.0.0' ๋ฐ”์ธ๋”ฉ ํ•„์ˆ˜

  • ์ฆ์ƒ: ๋กœ์ปฌ ๋จธ์‹ ์—์„œ๋Š” ์ž˜ ์ ‘์†๋˜์ง€๋งŒ, Docker ์ปจํ…Œ์ด๋„ˆ๋‚˜ Kubernetes Pod์— ๋ฐฐํฌํ•˜๋ฉด ์™ธ์ธก์—์„œ Connection Refused๊ฐ€ ๋ฐœ์ƒํ•จ.
  • ์›์ธ: Fastify์˜ ๊ธฐ๋ณธ ๋ฆฌ์Šจ ์ฃผ์†Œ๋Š” 127.0.0.1(localhost)์ž…๋‹ˆ๋‹ค. ์ปจํ…Œ์ด๋„ˆ ๋‚ด๋ถ€์˜ localhost๋Š” ์™ธ๋ถ€ ํฌํŠธ ํฌ์›Œ๋”ฉ์„ ์ˆ˜์‹ ํ•˜์ง€ ๋ชปํ•ฉ๋‹ˆ๋‹ค.
  • ํ•ด๊ฒฐ์ฑ…:
    await app.listen({ port: 3000, host: '0.0.0.0' });

โš ๏ธ 4. fast-json-stringify ์ง๋ ฌํ™”์— ์˜ํ•œ ํ•„๋“œ ๋ˆ„๋ฝ ์ฃผ์˜

  • ๋™์ž‘ ์›๋ฆฌ: Fastify๋Š” schema.response[200]์— ๋ช…์‹œ๋œ ์Šคํ‚ค๋งˆ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ C ์–ธ์–ด ์ˆ˜์ค€์˜ ๊ณ ์† ์ง๋ ฌํ™” ํ•จ์ˆ˜๋ฅผ ๋Ÿฐํƒ€์ž„์— ๋™์ ์œผ๋กœ ์ปดํŒŒ์ผ(JIT)ํ•ฉ๋‹ˆ๋‹ค.
  • ์ฃผ์˜์ : ํ•ธ๋“ค๋Ÿฌ์—์„œ ๋ฐ˜ํ™˜ํ•œ ๊ฐ์ฒด์— ์Šคํ‚ค๋งˆ์— ์ •์˜๋˜์ง€ ์•Š์€ ์ถ”๊ฐ€ ์†์„ฑ(extraProperty)์ด ํฌํ•จ๋˜์–ด ์žˆ๋”๋ผ๋„, ์Šคํ‚ค๋งˆ์— ์ ํ˜€์žˆ์ง€ ์•Š์€ ํ•„๋“œ๋Š” ์ตœ์ข… JSON ์‘๋‹ต์—์„œ ์ž๋™์œผ๋กœ ํ•„ํ„ฐ๋ง๋˜์–ด ๋ˆ„๋ฝ๋ฉ๋‹ˆ๋‹ค.
  • ์žฅ์ : ์˜๋„์น˜ ์•Š์€ ํŒจ์Šค์›Œ๋“œ ํ•ด์‹œ, ๋‚ด๋ถ€ ๋””๋ฒ„๊ทธ ํ”Œ๋ž˜๊ทธ ๋“ฑ ๋ฏผ๊ฐ ๋ฐ์ดํ„ฐ๊ฐ€ ์™ธ๋ถ€๋กœ ์œ ์ถœ๋˜๋Š” ์‚ฌ๊ณ ๋ฅผ ์›์ฒœ ๋ฐฉ์ง€ํ•ฉ๋‹ˆ๋‹ค.
  • ํŒ: ์‘๋‹ต์— ํŠน์ • ํ•„๋“œ๊ฐ€ ๋ˆ„๋ฝ๋œ๋‹ค๋ฉด schema.response ์ •์˜์— ํ•ด๋‹น ํ•„๋“œ๊ฐ€ ๋ˆ„๋ฝ๋˜์—ˆ๋Š”์ง€ ํ™•์ธํ•˜์‹ญ์‹œ์˜ค.

โš ๏ธ 5. ํ”„๋กœ๋•์…˜ Pino ๋กœ๊ฑฐ ์ตœ์ ํ™”

  • ๋กœ์ปฌ ๊ฐœ๋ฐœ ํ™˜๊ฒฝ์—์„œ๋Š” pino-pretty๊ฐ€ ํŽธ๋ฆฌํ•˜์ง€๋งŒ, CPU ๋ถ€ํ•˜๊ฐ€ ๋†’์œผ๋ฏ€๋กœ ํ”„๋กœ๋•์…˜์—์„œ๋Š” ๋ฐ˜๋“œ์‹œ ๊ธฐ๋ณธ Raw JSON ์ŠคํŠธ๋ฆผ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
  • ์ดˆ๋‹น ์ˆ˜๋งŒ ๊ฑด ์ด์ƒ์˜ ํŠธ๋ž˜ํ”ฝ์ด ๋ฐœ์ƒํ•˜๋Š” ํ™˜๊ฒฝ์—์„œ๋Š” pino.destination({ sync: false })๋ฅผ ์ ์šฉํ•˜์—ฌ ๋น„๋™๊ธฐ ๋ฒ„ํผ๋ง์„ ํ™œ์„ฑํ™”ํ•˜์‹ญ์‹œ์˜ค.

8. ์ž์ฃผ ์“ฐ์ด๋Š” Fastify ํ•ต์‹ฌ CLI & ์˜์กด์„ฑ ์š”์•ฝ

ํŒจํ‚ค์ง€๋ช…๋ชฉ์  ๋ฐ ํŠน์ง•์„ค์น˜ ๋ช…๋ น์–ด
fastifyFastify ํ•ต์‹ฌ ์›น ํ”„๋ ˆ์ž„์›Œํฌ ์—”์ง„pnpm add fastify
@fastify/type-provider-typeboxTypeBox ๊ธฐ๋ฐ˜ ์ปดํŒŒ์ผ ํƒ€์ž„ ํƒ€์ž… ์ถ”๋ก  ํ”Œ๋Ÿฌ๊ทธ์ธpnpm add @fastify/type-provider-typebox @sinclair/typebox
@fastify/type-provider-zodZod ์Šคํ‚ค๋งˆ ๊ฒ€์ฆ๊ธฐ ๋ฐ ์‹œ๋ฆฌ์–ผ๋ผ์ด์ € ๊ณต๊ธ‰์žpnpm add @fastify/type-provider-zod zod
fastify-pluginํ”Œ๋Ÿฌ๊ทธ์ธ ์บก์Аํ™”๋ฅผ ํ•ด์ œํ•˜๊ณ  ์ „์—ญ ์Šค์ฝ”ํ”„์— ์ฃผ์ž… (fp)pnpm add fastify-plugin
@fastify/swaggerOpenAPI 3.0 / Swagger ์ŠคํŽ™ ์ž๋™ ์ƒ์„ฑpnpm add @fastify/swagger
@fastify/swagger-ui๋Œ€ํ™”ํ˜• Swagger ์›น UI (/docs) ๋Œ€์‹œ๋ณด๋“œpnpm add @fastify/swagger-ui
@fastify/corsCross-Origin ๋ฆฌ์†Œ์Šค ๊ณต์œ  ํ—ค๋” ์„ค์ •pnpm add @fastify/cors
@fastify/helmet15๊ฐ€์ง€ ์ด์ƒ์˜ ํ‘œ์ค€ ๋ณด์•ˆ HTTP ์‘๋‹ต ํ—ค๋” ์ž๋™ ์ ์šฉpnpm add @fastify/helmet
@fastify/sensiblereply.notFound(), reply.badRequest() ๋“ฑ HTTP ํ—ฌํผpnpm add @fastify/sensible
@fastify/rate-limitIP ๋ฐ ํด๋ผ์ด์–ธํŠธ๋ณ„ API ํ˜ธ์ถœ ์†๋„ ์ œํ•œ ๊ฐ€๋“œpnpm add @fastify/rate-limit
@fastify/jwt์ดˆ๊ณ ์† JSON Web Token(JWT) ์„œ๋ช… ๋ฐ ๊ฒ€์ฆpnpm add @fastify/jwt
fastify-cliFastify ๊ณต์‹ ํ”„๋กœ์ ํŠธ ์Šค์บํด๋”ฉ ๋ฐ ์‹คํ–‰ CLInpm install -g fastify-cli
๐Ÿ’ฌ

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

0
0 / 1500