Files
nest-template/README.md
2026-04-14 11:49:30 +08:00

121 lines
3.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# NestJS Template
生產就緒的 NestJS 起始模板,內建常用基礎設施與規範,開新專案時直接 fork 使用。
## 技術棧
| 分類 | 套件 |
|---|---|
| 框架 | NestJS 11 |
| 語言 | TypeScript 5ESM + NodeNext |
| 資料庫 | PostgreSQL + TypeORM |
| 快取 | Redisioredis |
| 設定管理 | @nestjs/config |
| 驗證 | class-validator + class-transformer |
| 日誌 | nestjs-pino + pino-roll |
| 認證 | @nestjs/jwt |
| API 文件 | @nestjs/swagger |
| 流量控制 | @nestjs/throttler |
| 資安 | helmet + CORS |
## 內建功能
- **統一回傳格式** — 所有端點自動包裝為 `{ code, message, data }`
- **全域 JWT 驗證** — 預設所有路由需要 Bearer token公開路由加 `@Public()`
- **全域 Rate Limiting** — 透過環境變數設定 TTL 與上限次數
- **全域 ValidationPipe** — 自動過濾多餘欄位、型別轉換,自訂錯誤訊息
- **統一例外處理** — 所有例外回傳一致的錯誤格式
- **結構化日誌** — 開發環境 pretty printproduction 寫檔並自動輪替
- **Swagger UI** — 非 production 環境自動啟用,路徑 `/api/docs`
- **Graceful Shutdown** — 服務停止時正常關閉 DB / Redis 連線
## 快速開始
### 前置需求
- Node.js 22+
- pnpm
- PostgreSQL
- Redis
### 安裝
```bash
pnpm install
cp .env.example .env
```
編輯 `.env`填入資料庫、Redis、JWT 等設定值。
### 啟動
```bash
# 開發模式
pnpm start:dev
# 生產模式(需先 build
pnpm build
pnpm start:prod
```
## 環境變數
| 變數 | 說明 | 預設值 |
|---|---|---|
| `NODE_ENV` | 環境 | `development` |
| `PORT` | 監聽埠 | `3000` |
| `CORS_ORIGINS` | 允許的 CORS 來源,逗號分隔 | 空(全封) |
| `DB_HOST` | PostgreSQL 主機 | — |
| `DB_PORT` | PostgreSQL 埠 | `5432` |
| `DB_USER` | 使用者名稱 | — |
| `DB_PASSWORD` | 密碼 | — |
| `DB_NAME` | 資料庫名稱 | — |
| `REDIS_HOST` | Redis 主機 | — |
| `REDIS_PORT` | Redis 埠 | `6379` |
| `REDIS_USER` | Redis 使用者(選填) | — |
| `REDIS_PASSWORD` | Redis 密碼(選填) | — |
| `JWT_SECRET` | JWT 簽名金鑰 | — |
| `JWT_EXPIRES_IN` | Token 有效期 | `7d` |
| `THROTTLE_TTL` | Rate limit 時間窗口(毫秒) | — |
| `THROTTLE_LIMIT` | 時間窗口內最大請求數 | — |
## 目錄結構
```
src/
├── core/ # 生命週期類別 + 基礎設施模組
│ ├── db/ # TypeORM 設定
│ ├── redis/ # Redis 設定
│ ├── logger/ # Pino 日誌設定
│ ├── throttler/ # Rate limiting 設定
│ ├── filter/ # 全域例外 filter
│ ├── interceptor/ # 回應包裝 interceptor
│ ├── guard/ # JWT guard
│ └── pipe/ # Validation exception factory
├── common/ # 跨模組共用(不掛生命週期)
│ ├── decorator/ # @Public() 等自訂裝飾器
│ ├── token/ # 注入 token 常數
│ └── type/ # 共用型別ApiResponse、JwtPayload
└── module/ # 業務功能模組(每個領域一個子目錄)
```
新業務模組放在 `src/module/<模組名>/`,結構參考 `CLAUDE.md`
## 常用指令
```bash
pnpm start:dev # 開發模式watch
pnpm start:debug # 除錯模式
pnpm build # 編譯
pnpm typecheck # 型別檢查
pnpm lint # Lint 檢查
pnpm format # 格式化
pnpm test # 單元測試
pnpm test:cov # 測試覆蓋率
pnpm test:e2e # E2E 測試
```
## 開發規範
詳見 [CLAUDE.md](./CLAUDE.md)。