generated from ttipo/project-base
Initial commit
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
# ==========================================
|
||||
# 백엔드 고유 시크릿 (development)
|
||||
#
|
||||
# ⚠️ DB / Redis / CORS / PORT 는 루트 .env.development 에서 docker-compose 가 주입한다.
|
||||
# 여기에 중복 작성하지 말 것 (SSOT: 루트 .env — .claude/rules/env-structure.md).
|
||||
# 이 파일에는 "루트에서 내려주지 않는 값"만 작성한다.
|
||||
#
|
||||
# 사용법: cp .env.development.example .env.development
|
||||
# docker-compose 의 env_file 지시자 때문에 파일은 비어 있어도 존재해야 한다.
|
||||
# ==========================================
|
||||
|
||||
# JWT 서명 키 — 인증 도입 시 사용. 환경마다 다른 값을 쓰고 절대 커밋하지 않는다.
|
||||
JWT_SECRET=change-me-generate-a-long-random-string
|
||||
JWT_ACCESS_EXPIRES_IN=1h
|
||||
JWT_REFRESH_EXPIRES_IN=14d
|
||||
@@ -0,0 +1,15 @@
|
||||
# ==========================================
|
||||
# 백엔드 고유 시크릿 (production)
|
||||
#
|
||||
# ⚠️ DB / Redis / CORS / PORT 는 루트 .env.production 에서 docker-compose 가 주입한다.
|
||||
# 여기에 중복 작성하지 말 것 (SSOT: 루트 .env — .claude/rules/env-structure.md).
|
||||
# 이 파일에는 "루트에서 내려주지 않는 값"만 작성한다.
|
||||
#
|
||||
# 사용법: cp .env.production.example .env.production
|
||||
# docker-compose 의 env_file 지시자 때문에 파일은 비어 있어도 존재해야 한다.
|
||||
# ==========================================
|
||||
|
||||
# JWT 서명 키 — 인증 도입 시 사용. 환경마다 다른 값을 쓰고 절대 커밋하지 않는다.
|
||||
JWT_SECRET=change-me-generate-a-long-random-string
|
||||
JWT_ACCESS_EXPIRES_IN=1h
|
||||
JWT_REFRESH_EXPIRES_IN=14d
|
||||
@@ -0,0 +1,58 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Tests
|
||||
/coverage
|
||||
/.nyc_output
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
.env.development
|
||||
.env.production
|
||||
|
||||
# temp directory
|
||||
.temp
|
||||
.tmp
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
FROM node:20-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
# 호스트의 npm 11 이 작성한 package-lock.json 형식과 호환되도록 npm 을 11 로 업그레이드
|
||||
# (전역 설치는 root 권한이 필요하므로 USER 전환 전에 수행)
|
||||
RUN npm install -g npm@11
|
||||
|
||||
# 개발 환경(docker-compose.dev.yml)은 이 스테이지를 그대로 구동하므로 비-root 로 전환한다.
|
||||
# /app 소유권을 넘겨야 익명 볼륨(node_modules)도 node 소유로 생성되어 캐시 쓰기가 가능하다.
|
||||
RUN chown node:node /app
|
||||
USER node
|
||||
|
||||
# 재현 가능한 빌드를 위해 npm ci 사용 (lockfile 기반)
|
||||
COPY --chown=node:node package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY --chown=node:node . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine AS production
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
# 운영 stage 도 동일 npm 버전 사용
|
||||
RUN npm install -g npm@11
|
||||
|
||||
# 운영용 의존성만 설치
|
||||
COPY package*.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
# 비-root 실행 (보안 규칙)
|
||||
USER node
|
||||
|
||||
CMD ["node", "dist/main"]
|
||||
@@ -0,0 +1,98 @@
|
||||
<p align="center">
|
||||
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||
</p>
|
||||
|
||||
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||
|
||||
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||
</p>
|
||||
<!--[](https://opencollective.com/nest#backer)
|
||||
[](https://opencollective.com/nest#sponsor)-->
|
||||
|
||||
## Description
|
||||
|
||||
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||
|
||||
## Project setup
|
||||
|
||||
```bash
|
||||
$ npm install
|
||||
```
|
||||
|
||||
## Compile and run the project
|
||||
|
||||
```bash
|
||||
# development
|
||||
$ npm run start
|
||||
|
||||
# watch mode
|
||||
$ npm run start:dev
|
||||
|
||||
# production mode
|
||||
$ npm run start:prod
|
||||
```
|
||||
|
||||
## Run tests
|
||||
|
||||
```bash
|
||||
# unit tests
|
||||
$ npm run test
|
||||
|
||||
# e2e tests
|
||||
$ npm run test:e2e
|
||||
|
||||
# test coverage
|
||||
$ npm run test:cov
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||
|
||||
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||
|
||||
```bash
|
||||
$ npm install -g @nestjs/mau
|
||||
$ mau deploy
|
||||
```
|
||||
|
||||
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||
|
||||
## Resources
|
||||
|
||||
Check out a few resources that may come in handy when working with NestJS:
|
||||
|
||||
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||
|
||||
## Support
|
||||
|
||||
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||
|
||||
## Stay in touch
|
||||
|
||||
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||
|
||||
## License
|
||||
|
||||
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||
@@ -0,0 +1,67 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
{
|
||||
ignores: ['eslint.config.mjs', 'dist/**', 'coverage/**'],
|
||||
},
|
||||
eslint.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
eslintPluginPrettierRecommended,
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.node,
|
||||
...globals.jest,
|
||||
},
|
||||
sourceType: 'commonjs',
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
rules: {
|
||||
// 타입 규칙 — 명시적 타입 선언 강제 ([[coding-common]])
|
||||
'@typescript-eslint/no-explicit-any': 'error',
|
||||
// 비동기 누락은 조용한 버그가 되므로 error 로 승격
|
||||
'@typescript-eslint/no-floating-promises': 'error',
|
||||
'@typescript-eslint/no-unsafe-argument': 'error',
|
||||
|
||||
// 로깅 규칙 — console 대신 winston/Nest Logger 사용 ([[logging]])
|
||||
'no-console': 'error',
|
||||
|
||||
// 에러 규칙 — 코드 없는 실패 금지. HttpException 직접 상속/생성 대신
|
||||
// BusinessException 을 사용한다 ([[error-codes]])
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{
|
||||
selector:
|
||||
"NewExpression[callee.name='HttpException']:not([callee.name='BusinessException'])",
|
||||
message:
|
||||
'HttpException 을 직접 생성하지 말고 BusinessException(code) 을 사용하세요. (.claude/rules/error-codes.md)',
|
||||
},
|
||||
],
|
||||
|
||||
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
||||
},
|
||||
},
|
||||
{
|
||||
// 에러 코드 레지스트리·예외 필터는 프레임워크 예외를 직접 다루는 계층이므로 예외 허용
|
||||
files: ['src/common/errors/**/*.ts', 'src/common/filters/**/*.ts'],
|
||||
rules: {
|
||||
'no-restricted-syntax': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
// CLI 스크립트는 콘솔 출력이 정상 동작이다
|
||||
files: ['scripts/**/*.ts'],
|
||||
rules: {
|
||||
'no-console': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/nest-cli",
|
||||
"collection": "@nestjs/schematics",
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"deleteOutDir": true,
|
||||
"builder": "swc",
|
||||
"typeCheck": true
|
||||
}
|
||||
}
|
||||
Generated
+13609
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "0.0.1",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"lint": "eslint \"{src,apps,libs,test,scripts}/**/*.ts\" --max-warnings 0",
|
||||
"lint:fix": "eslint \"{src,apps,libs,test,scripts}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:cov": "jest --coverage",
|
||||
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||
"sync:error-codes": "ts-node -P tsconfig.json scripts/sync-error-codes.ts",
|
||||
"typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js -d src/data-source.ts",
|
||||
"migration:generate": "npm run typeorm -- migration:generate",
|
||||
"migration:create": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:create",
|
||||
"migration:run": "npm run typeorm -- migration:run",
|
||||
"migration:revert": "npm run typeorm -- migration:revert",
|
||||
"migration:show": "npm run typeorm -- migration:show"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/cache-manager": "^3.0.1",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.3",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/schedule": "^6.1.1",
|
||||
"@nestjs/swagger": "^11.2.6",
|
||||
"@nestjs/terminus": "^11.0.0",
|
||||
"@nestjs/throttler": "^6.4.0",
|
||||
"@nestjs/typeorm": "^11.0.1",
|
||||
"cache-manager": "^6.4.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"helmet": "^8.1.0",
|
||||
"nest-winston": "^1.10.0",
|
||||
"pg": "^8.20.0",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.28",
|
||||
"winston": "^3.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@swc/cli": "^0.8.1",
|
||||
"@swc/core": "^1.15.24",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/multer": "^2.2.0",
|
||||
"@types/node": "^22.10.7",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"chokidar": "^5.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^16.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"prettier": "^3.4.2",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
},
|
||||
"overrides": {
|
||||
"multer": "^2.4.0"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"moduleNameMapper": {
|
||||
"^@/(.*)$": "<rootDir>/$1"
|
||||
},
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
},
|
||||
"collectCoverageFrom": [
|
||||
"**/*.(t|j)s"
|
||||
],
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* 에러 코드 SSOT 동기화 스크립트.
|
||||
*
|
||||
* backend 의 error-codes.ts 레지스트리를 읽어 프론트엔드/플러터의 에러 사전을 생성한다.
|
||||
* 실행: npm run sync:error-codes (backend 디렉터리에서)
|
||||
*
|
||||
* 생성 파일은 직접 수정하지 말 것 — 레지스트리를 고치고 다시 실행한다.
|
||||
* CI 는 이 스크립트를 실행한 뒤 git diff 로 드리프트를 검사한다.
|
||||
*/
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
|
||||
import { ERROR_CODES } from '../src/common/errors/error-codes';
|
||||
|
||||
const REPO_ROOT = resolve(__dirname, '..', '..');
|
||||
|
||||
// 이 스크립트는 저장소 루트 기준으로 frontend/·flutter/ 에 파일을 쓴다.
|
||||
// 컨테이너 안에서는 backend/ 만 마운트되어 형제 디렉터리가 없으므로 실행할 수 없다.
|
||||
if (!existsSync(resolve(REPO_ROOT, 'frontend'))) {
|
||||
console.error(
|
||||
[
|
||||
'저장소 루트를 찾을 수 없습니다: ' + REPO_ROOT,
|
||||
'',
|
||||
'이 스크립트는 frontend/·flutter/ 에 사전 파일을 생성하므로',
|
||||
'저장소 전체가 보이는 곳에서 실행해야 합니다.',
|
||||
'컨테이너 안(backend/ 만 마운트됨)이 아니라 **호스트에서** 실행하세요:',
|
||||
' cd backend && npm run sync:error-codes',
|
||||
].join('\n'),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const GENERATED_NOTICE =
|
||||
'backend/src/common/errors/error-codes.ts 에서 자동 생성된 파일입니다. 직접 수정하지 마세요.';
|
||||
|
||||
const entries = Object.entries(ERROR_CODES);
|
||||
|
||||
/** TypeScript 작은따옴표 문자열 리터럴로 이스케이프한다. */
|
||||
function toTsLiteral(value: string): string {
|
||||
const escaped = value
|
||||
.split('\\')
|
||||
.join('\\\\')
|
||||
.split("'")
|
||||
.join('\\' + "'");
|
||||
return `'${escaped}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dart 작은따옴표 문자열 리터럴로 이스케이프한다.
|
||||
* Dart 는 문자열 안의 `$` 를 보간으로 해석하므로 함께 이스케이프해야 한다.
|
||||
*/
|
||||
function toDartLiteral(value: string): string {
|
||||
const escaped = value
|
||||
.split('\\')
|
||||
.join('\\\\')
|
||||
.split("'")
|
||||
.join('\\' + "'")
|
||||
.split('$')
|
||||
.join('\\' + '$');
|
||||
return `'${escaped}'`;
|
||||
}
|
||||
|
||||
function writeGenerated(relativePath: string, content: string): void {
|
||||
const target = resolve(REPO_ROOT, relativePath);
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, content, { encoding: 'utf8' });
|
||||
console.log(`생성 완료: ${relativePath}`);
|
||||
}
|
||||
|
||||
// ---------- frontend (TypeScript) ----------
|
||||
const tsBody = entries
|
||||
.map(([code, def]) => ` ${code}: ${toTsLiteral(def.message)},`)
|
||||
.join('\n');
|
||||
|
||||
writeGenerated(
|
||||
'frontend/src/shared/constants/error-codes.generated.ts',
|
||||
`// ${GENERATED_NOTICE}\n\n` +
|
||||
`export const ERROR_CODE_MESSAGES = {\n${tsBody}\n} as const\n\n` +
|
||||
`export type ErrorCode = keyof typeof ERROR_CODE_MESSAGES\n\n` +
|
||||
`/** 매핑 실패 시 사용하는 폴백 코드 */\n` +
|
||||
`export const FALLBACK_ERROR_CODE: ErrorCode = 'SYS_001'\n`,
|
||||
);
|
||||
|
||||
// ---------- flutter (Dart) ----------
|
||||
const dartBody = entries
|
||||
.map(([code, def]) => ` '${code}': ${toDartLiteral(def.message)},`)
|
||||
.join('\n');
|
||||
|
||||
writeGenerated(
|
||||
'flutter/lib/core/api/error_lexicon.g.dart',
|
||||
`// ${GENERATED_NOTICE}\n\n` +
|
||||
`const Map<String, String> kErrorCodeMessages = {\n${dartBody}\n};\n\n` +
|
||||
`/// 매핑 실패 시 사용하는 폴백 코드\n` +
|
||||
`const String kFallbackErrorCode = 'SYS_001';\n`,
|
||||
);
|
||||
|
||||
console.log(`\n총 ${entries.length}개 에러 코드를 동기화했습니다.`);
|
||||
@@ -0,0 +1,77 @@
|
||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
|
||||
import { RequestIdMiddleware } from '@/common/middleware/request-id.middleware';
|
||||
import { HealthModule } from '@/modules/health/health.module';
|
||||
import { UploadModule } from '@/modules/upload/upload.module';
|
||||
import { UserModule } from '@/modules/user/user.module';
|
||||
import { parsePositiveInt } from '@/shared/utils/env';
|
||||
import { buildDatabaseOptions } from '@/shared/config/database.config';
|
||||
import { validateEnv } from '@/shared/config/env.validation';
|
||||
import { ShutdownLogger } from '@/shared/logger/shutdown.logger';
|
||||
|
||||
// Rate Limiting 기본 정책 — 루트 .env 의 THROTTLE_* 로 덮어쓸 수 있다 (.claude/rules/env-structure.md)
|
||||
const THROTTLE_DEFAULT_TTL_MS = 60_000; // 집계 구간: 60초
|
||||
const THROTTLE_DEFAULT_LIMIT = 100; // 구간당 IP별 최대 요청 수
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ScheduleModule.forRoot(),
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
envFilePath: `.env.${process.env.NODE_ENV || 'development'}`,
|
||||
// 설정이 잘못되면 조용히 기본값으로 굴러가지 않고 기동 시점에 실패시킨다
|
||||
validate: validateEnv,
|
||||
}),
|
||||
// 전역 캐시 매니저 — Redis 도입 시 store 옵션을 redisStore 로 변경
|
||||
CacheModule.register({
|
||||
isGlobal: true,
|
||||
ttl: 60_000, // 60초 기본 TTL
|
||||
}),
|
||||
// 전역 Rate Limiter — API 남용/브루트포스 방지 (프로젝트의 유일한 rate limiting 수단)
|
||||
// 한도 초과 시 429 → 전역 필터가 REQ_001 로 매핑한다.
|
||||
// 라우트 단위 조정은 @Throttle({ default: { ttl, limit } }), 제외는 @SkipThrottle().
|
||||
ThrottlerModule.forRoot([
|
||||
{
|
||||
// compose 가 미정의 변수를 빈 문자열로 주입하므로 parsePositiveInt 로 방어한다
|
||||
ttl: parsePositiveInt(
|
||||
process.env.THROTTLE_TTL_MS,
|
||||
THROTTLE_DEFAULT_TTL_MS,
|
||||
),
|
||||
limit: parsePositiveInt(
|
||||
process.env.THROTTLE_LIMIT,
|
||||
THROTTLE_DEFAULT_LIMIT,
|
||||
),
|
||||
},
|
||||
]),
|
||||
// DB 접속 설정은 database.config.ts 하나만 수정한다 (CLI 와 공유)
|
||||
TypeOrmModule.forRootAsync({
|
||||
useFactory: () => ({
|
||||
...buildDatabaseOptions(),
|
||||
// Nest 모듈에 등록된 엔티티를 자동으로 수집한다 (CLI 는 glob 경로를 사용)
|
||||
autoLoadEntities: true,
|
||||
}),
|
||||
}),
|
||||
HealthModule,
|
||||
UploadModule,
|
||||
UserModule,
|
||||
],
|
||||
providers: [
|
||||
ShutdownLogger,
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule implements NestModule {
|
||||
// 모든 요청에 추적 ID 를 부여한다 (로그·에러 응답 traceId 와 동일 값)
|
||||
configure(consumer: MiddlewareConsumer): void {
|
||||
consumer.apply(RequestIdMiddleware).forRoutes('*');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Type, applyDecorators } from '@nestjs/common';
|
||||
import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';
|
||||
|
||||
import { ErrorCode, getErrorDefinition } from '@/common/errors/error-codes';
|
||||
|
||||
/**
|
||||
* Swagger 문서를 실제 응답(표준 래퍼)과 일치시킨다.
|
||||
* 컨트롤러는 raw 데이터를 반환하지만 클라이언트가 받는 본문은 { success, data } 이므로,
|
||||
* `@ApiResponse({ type: Dto })` 를 그대로 쓰면 문서와 실응답이 어긋난다.
|
||||
*
|
||||
* 사용 예:
|
||||
* @ApiStandardResponse(UserResponseDto, { status: 200, description: '사용자 조회 성공' })
|
||||
*/
|
||||
export function ApiStandardResponse<TModel extends Type<unknown>>(
|
||||
model?: TModel,
|
||||
options: { status?: number; description?: string; isArray?: boolean } = {},
|
||||
) {
|
||||
const { status = 200, description = '요청 성공', isArray = false } = options;
|
||||
|
||||
const dataSchema = model
|
||||
? isArray
|
||||
? { type: 'array', items: { $ref: getSchemaPath(model) } }
|
||||
: { $ref: getSchemaPath(model) }
|
||||
: { type: 'object', nullable: true };
|
||||
|
||||
return applyDecorators(
|
||||
...(model ? [ApiExtraModels(model)] : []),
|
||||
ApiResponse({
|
||||
status,
|
||||
description,
|
||||
schema: {
|
||||
properties: {
|
||||
success: { type: 'boolean', example: true },
|
||||
data: dataSchema,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 표준 실패 응답을 에러 코드와 함께 문서화한다.
|
||||
* 상태 코드·메시지는 레지스트리에서 가져오므로 문서와 구현이 자동으로 일치한다.
|
||||
*
|
||||
* 사용 예:
|
||||
* @ApiErrorResponse('RES_001', '사용자를 찾을 수 없음')
|
||||
*/
|
||||
export function ApiErrorResponse(code: ErrorCode, description?: string) {
|
||||
const definition = getErrorDefinition(code);
|
||||
|
||||
return ApiResponse({
|
||||
status: definition.status,
|
||||
description: description ?? definition.message,
|
||||
schema: {
|
||||
properties: {
|
||||
success: { type: 'boolean', example: false },
|
||||
error: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
code: { type: 'string', example: code },
|
||||
message: { type: 'string', example: definition.message },
|
||||
traceId: {
|
||||
type: 'string',
|
||||
example: '3f1c0a2e-0f1b-4f2a-9a1e-6c9f0a1b2c3d',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const SKIP_TRANSFORM_KEY = 'skipTransform';
|
||||
|
||||
/**
|
||||
* 표준 응답 래핑({ success, data })을 건너뛴다.
|
||||
* 파일 다운로드·스트림·리다이렉트·204 No Content 처럼
|
||||
* 본문 구조를 바꾸면 안 되는 핸들러에만 사용한다.
|
||||
*/
|
||||
export const SkipTransform = () => SetMetadata(SKIP_TRANSFORM_KEY, true);
|
||||
@@ -0,0 +1,99 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
|
||||
|
||||
/** 페이지네이션 기본값 — 매직 넘버 방지용 상수 */
|
||||
export const PAGINATION_DEFAULT_LIMIT = 20;
|
||||
export const PAGINATION_MAX_LIMIT = 100;
|
||||
|
||||
/** 커서 기반 페이지네이션 쿼리 (목록 API 기본 권장) */
|
||||
export class CursorPaginationQueryDto {
|
||||
@ApiPropertyOptional({
|
||||
description: '이전 응답의 nextCursor 값. 첫 페이지는 생략한다.',
|
||||
example: 'eyJpZCI6MTIzfQ==',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString({ message: '커서 값의 형식이 올바르지 않습니다.' })
|
||||
cursor?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: `한 번에 가져올 개수 (1~${PAGINATION_MAX_LIMIT})`,
|
||||
default: PAGINATION_DEFAULT_LIMIT,
|
||||
example: PAGINATION_DEFAULT_LIMIT,
|
||||
})
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt({ message: '조회 개수는 정수로 입력해 주세요.' })
|
||||
@Min(1, { message: '조회 개수는 1 이상이어야 합니다.' })
|
||||
@Max(PAGINATION_MAX_LIMIT, {
|
||||
message: `조회 개수는 ${PAGINATION_MAX_LIMIT} 이하여야 합니다.`,
|
||||
})
|
||||
limit: number = PAGINATION_DEFAULT_LIMIT;
|
||||
}
|
||||
|
||||
/** 오프셋 기반 페이지네이션 쿼리 (전체 페이지 수가 필요한 화면에서만 사용) */
|
||||
export class OffsetPaginationQueryDto {
|
||||
@ApiPropertyOptional({
|
||||
description: '1부터 시작하는 페이지 번호',
|
||||
default: 1,
|
||||
})
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt({ message: '페이지 번호는 정수로 입력해 주세요.' })
|
||||
@Min(1, { message: '페이지 번호는 1 이상이어야 합니다.' })
|
||||
page: number = 1;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: `한 페이지 개수 (1~${PAGINATION_MAX_LIMIT})`,
|
||||
default: PAGINATION_DEFAULT_LIMIT,
|
||||
})
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt({ message: '조회 개수는 정수로 입력해 주세요.' })
|
||||
@Min(1, { message: '조회 개수는 1 이상이어야 합니다.' })
|
||||
@Max(PAGINATION_MAX_LIMIT, {
|
||||
message: `조회 개수는 ${PAGINATION_MAX_LIMIT} 이하여야 합니다.`,
|
||||
})
|
||||
limit: number = PAGINATION_DEFAULT_LIMIT;
|
||||
}
|
||||
|
||||
/** 목록 응답의 페이지 정보 — 세 플랫폼 공유 계약 */
|
||||
export class PageInfoDto {
|
||||
@ApiProperty({ description: '다음 페이지 존재 여부', example: true })
|
||||
hasNext!: boolean;
|
||||
|
||||
@ApiProperty({
|
||||
description: '다음 요청에 넘길 커서. 마지막 페이지면 null',
|
||||
nullable: true,
|
||||
example: 'eyJpZCI6MTQzfQ==',
|
||||
})
|
||||
nextCursor!: string | null;
|
||||
|
||||
@ApiProperty({
|
||||
description: '전체 개수. 계산 비용이 큰 경우 null 을 반환할 수 있다.',
|
||||
nullable: true,
|
||||
example: 143,
|
||||
})
|
||||
total!: number | null;
|
||||
}
|
||||
|
||||
/** 목록 응답 본문 — 인터셉터가 { success, data } 로 한 번 더 감싼다. */
|
||||
export interface PaginatedResult<T> {
|
||||
items: T[];
|
||||
pageInfo: PageInfoDto;
|
||||
}
|
||||
|
||||
/** 조회 결과를 표준 목록 응답으로 변환한다. */
|
||||
export function toPaginatedResult<T>(
|
||||
items: T[],
|
||||
pageInfo: Partial<PageInfoDto> = {},
|
||||
): PaginatedResult<T> {
|
||||
return {
|
||||
items,
|
||||
pageInfo: {
|
||||
hasNext: pageInfo.hasNext ?? false,
|
||||
nextCursor: pageInfo.nextCursor ?? null,
|
||||
total: pageInfo.total ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { HttpException } from '@nestjs/common';
|
||||
|
||||
import { ErrorCode, getErrorDefinition } from './error-codes';
|
||||
|
||||
export interface BusinessExceptionOptions {
|
||||
/** 레지스트리 기본 메시지 대신 사용자에게 보여줄 문구 (동적 값이 필요한 경우만) */
|
||||
readonly message?: string;
|
||||
/** 로그에만 남기는 개발자용 컨텍스트 — 응답 본문에는 포함되지 않는다 */
|
||||
readonly context?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자에게 노출되는 모든 실패는 이 예외로 던진다.
|
||||
* 에러 코드가 생성자 필수 인자이므로, 코드 없는 에러가 만들어질 수 없다.
|
||||
*
|
||||
* 사용 예:
|
||||
* throw new BusinessException('RES_001');
|
||||
* throw new BusinessException('USER_001', { context: { email } });
|
||||
*/
|
||||
export class BusinessException extends HttpException {
|
||||
readonly code: ErrorCode;
|
||||
readonly context?: Record<string, unknown>;
|
||||
|
||||
constructor(code: ErrorCode, options: BusinessExceptionOptions = {}) {
|
||||
const definition = getErrorDefinition(code);
|
||||
const message = options.message ?? definition.message;
|
||||
|
||||
super({ code, message }, definition.status);
|
||||
|
||||
this.code = code;
|
||||
this.context = options.context;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
|
||||
import {
|
||||
ERROR_CODES,
|
||||
FALLBACK_ERROR_CODE,
|
||||
getErrorDefinition,
|
||||
isErrorCode,
|
||||
resolveCodeByStatus,
|
||||
} from './error-codes';
|
||||
import { BusinessException } from './business.exception';
|
||||
|
||||
describe('에러 코드 레지스트리', () => {
|
||||
it('모든 코드는 DOMAIN_NNN 네이밍 규약을 따른다', () => {
|
||||
for (const code of Object.keys(ERROR_CODES)) {
|
||||
expect(code).toMatch(/^[A-Z]+_\d{3}$/);
|
||||
}
|
||||
});
|
||||
|
||||
it('모든 코드는 메시지와 HTTP 상태를 갖는다', () => {
|
||||
for (const [code, definition] of Object.entries(ERROR_CODES)) {
|
||||
expect(definition.message.length).toBeGreaterThan(0);
|
||||
expect(definition.status).toBeGreaterThanOrEqual(400);
|
||||
expect(code).not.toBe('');
|
||||
}
|
||||
});
|
||||
|
||||
it('미등록 코드는 폴백(SYS_001) 정의를 반환한다', () => {
|
||||
expect(getErrorDefinition('UNKNOWN_999')).toBe(
|
||||
ERROR_CODES[FALLBACK_ERROR_CODE],
|
||||
);
|
||||
expect(isErrorCode('UNKNOWN_999')).toBe(false);
|
||||
});
|
||||
|
||||
it('HTTP 상태 코드를 대응하는 에러 코드로 역매핑한다', () => {
|
||||
expect(resolveCodeByStatus(HttpStatus.UNAUTHORIZED)).toBe('AUTH_001');
|
||||
expect(resolveCodeByStatus(HttpStatus.FORBIDDEN)).toBe('AUTH_003');
|
||||
expect(resolveCodeByStatus(HttpStatus.NOT_FOUND)).toBe('RES_001');
|
||||
expect(resolveCodeByStatus(HttpStatus.BAD_REQUEST)).toBe('VAL_001');
|
||||
expect(resolveCodeByStatus(HttpStatus.TOO_MANY_REQUESTS)).toBe('REQ_001');
|
||||
});
|
||||
|
||||
it('매핑되지 않은 4xx 는 BIZ_001, 5xx 는 SYS_001 로 수렴한다', () => {
|
||||
expect(resolveCodeByStatus(HttpStatus.CONFLICT)).toBe('BIZ_001');
|
||||
expect(resolveCodeByStatus(HttpStatus.BAD_GATEWAY)).toBe('SYS_001');
|
||||
});
|
||||
|
||||
it('클라이언트 전용 코드(AUTH_002)는 서버가 상태 역매핑으로 선택하지 않는다', () => {
|
||||
const clientOnlyCodes = Object.entries(ERROR_CODES)
|
||||
.filter(([, definition]) => definition.clientOnly)
|
||||
.map(([code]) => code);
|
||||
|
||||
expect(clientOnlyCodes).toContain('AUTH_002');
|
||||
|
||||
// 모든 4xx/5xx 상태에 대해 clientOnly 코드가 선택되지 않아야 한다.
|
||||
for (let status = 400; status < 600; status += 1) {
|
||||
expect(clientOnlyCodes).not.toContain(resolveCodeByStatus(status));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('BusinessException', () => {
|
||||
it('레지스트리의 상태 코드와 메시지를 그대로 사용한다', () => {
|
||||
const exception = new BusinessException('RES_001');
|
||||
|
||||
expect(exception.getStatus()).toBe(HttpStatus.NOT_FOUND);
|
||||
expect(exception.getResponse()).toEqual({
|
||||
code: 'RES_001',
|
||||
message: ERROR_CODES.RES_001.message,
|
||||
});
|
||||
});
|
||||
|
||||
it('메시지를 재정의해도 코드와 상태는 유지된다', () => {
|
||||
const exception = new BusinessException('BIZ_001', {
|
||||
message: '이미 가입된 이메일입니다.',
|
||||
context: { email: 'user@example.com' },
|
||||
});
|
||||
|
||||
expect(exception.code).toBe('BIZ_001');
|
||||
expect(exception.getStatus()).toBe(HttpStatus.BAD_REQUEST);
|
||||
expect(exception.getResponse()).toEqual({
|
||||
code: 'BIZ_001',
|
||||
message: '이미 가입된 이메일입니다.',
|
||||
});
|
||||
// context 는 로그 전용이며 응답 본문에 포함되지 않는다.
|
||||
expect(exception.context).toEqual({ email: 'user@example.com' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* 에러 코드 레지스트리 — 세 플랫폼(backend / frontend / flutter)이 공유하는 단일 진실 공급원(SSOT).
|
||||
*
|
||||
* 이 파일만 수정한 뒤 `npm run sync:error-codes` 를 실행하면
|
||||
* 프론트엔드/플러터의 에러 사전이 자동 생성된다. (수동 복사 금지)
|
||||
*/
|
||||
|
||||
export interface ErrorCodeDefinition {
|
||||
/** 이 코드로 응답할 때 사용할 HTTP 상태 코드 */
|
||||
readonly status: HttpStatus;
|
||||
/** 사용자에게 노출되는 한국어 메시지 */
|
||||
readonly message: string;
|
||||
/** true 면 클라이언트에서만 생성하는 코드 — 서버 응답에는 절대 나타나지 않는다 */
|
||||
readonly clientOnly?: true;
|
||||
}
|
||||
|
||||
// 공통 코드 — 모든 도메인이 공유한다.
|
||||
const COMMON_ERROR_CODES = {
|
||||
SYS_001: {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
message: '일시적인 시스템 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.',
|
||||
},
|
||||
REQ_001: {
|
||||
status: HttpStatus.TOO_MANY_REQUESTS,
|
||||
message: '요청이 너무 많습니다. 잠시 후 다시 시도해 주세요.',
|
||||
},
|
||||
AUTH_001: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: '로그인이 필요한 서비스입니다. 로그인 후 이용해 주세요.',
|
||||
},
|
||||
AUTH_002: {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
message: '안전을 위해 로그아웃 되었습니다. 다시 로그인해 주세요.',
|
||||
// 세션 만료는 클라이언트가 "인증된 세션이 있었는데 401 을 받은" 상황에서 생성한다.
|
||||
clientOnly: true,
|
||||
},
|
||||
AUTH_003: {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
message: '해당 메뉴나 기능에 접근할 수 있는 권한이 없습니다.',
|
||||
},
|
||||
VAL_001: {
|
||||
status: HttpStatus.BAD_REQUEST,
|
||||
message: '입력하신 정보를 다시 확인해 주세요. (필수값 누락 또는 형식 오류)',
|
||||
},
|
||||
RES_001: {
|
||||
status: HttpStatus.NOT_FOUND,
|
||||
message: '요청하신 정보나 페이지를 찾을 수 없습니다.',
|
||||
},
|
||||
BIZ_001: {
|
||||
status: HttpStatus.BAD_REQUEST,
|
||||
message: '요청하신 작업을 완료하지 못했습니다. 다시 시도해 주세요.',
|
||||
},
|
||||
} as const satisfies Record<string, ErrorCodeDefinition>;
|
||||
|
||||
/**
|
||||
* 도메인 코드 — 기능 추가 시 여기에 `DOMAIN_NNN` 형식으로 등록한다.
|
||||
* 번호는 001 부터 순차 부여하고, 한번 배포된 코드의 의미는 바꾸지 않는다(폐기 시 주석으로 표시).
|
||||
*
|
||||
* 예시:
|
||||
* USER_001: {
|
||||
* status: HttpStatus.CONFLICT,
|
||||
* message: '이미 가입된 이메일입니다. 다른 이메일을 사용해 주세요.',
|
||||
* },
|
||||
*/
|
||||
const DOMAIN_ERROR_CODES = {
|
||||
FILE_001: {
|
||||
status: HttpStatus.BAD_REQUEST,
|
||||
message: '허용되지 않는 파일 형식입니다. 파일을 확인해 주세요.',
|
||||
},
|
||||
FILE_002: {
|
||||
status: HttpStatus.PAYLOAD_TOO_LARGE,
|
||||
message: '파일 크기가 허용 범위를 초과했습니다.',
|
||||
},
|
||||
} as const satisfies Record<string, ErrorCodeDefinition>;
|
||||
|
||||
export const ERROR_CODES = {
|
||||
...COMMON_ERROR_CODES,
|
||||
...DOMAIN_ERROR_CODES,
|
||||
} as const;
|
||||
|
||||
export type ErrorCode = keyof typeof ERROR_CODES;
|
||||
|
||||
/** 매핑에 실패했을 때 사용하는 최종 폴백 코드 */
|
||||
export const FALLBACK_ERROR_CODE: ErrorCode = 'SYS_001';
|
||||
|
||||
/** HTTP 상태 코드 → 에러 코드 폴백 매핑 (프레임워크가 던진 HttpException 용) */
|
||||
const STATUS_TO_ERROR_CODE: ReadonlyMap<number, ErrorCode> = new Map<
|
||||
number,
|
||||
ErrorCode
|
||||
>([
|
||||
[HttpStatus.UNAUTHORIZED, 'AUTH_001'],
|
||||
[HttpStatus.FORBIDDEN, 'AUTH_003'],
|
||||
[HttpStatus.NOT_FOUND, 'RES_001'],
|
||||
[HttpStatus.BAD_REQUEST, 'VAL_001'],
|
||||
[HttpStatus.UNPROCESSABLE_ENTITY, 'VAL_001'],
|
||||
[HttpStatus.TOO_MANY_REQUESTS, 'REQ_001'],
|
||||
// multer 가 파일 크기 한도 초과 시 던지는 상태 코드
|
||||
[HttpStatus.PAYLOAD_TOO_LARGE, 'FILE_002'],
|
||||
]);
|
||||
|
||||
/** 등록된 에러 코드인지 확인한다. */
|
||||
export function isErrorCode(code: string): code is ErrorCode {
|
||||
return Object.prototype.hasOwnProperty.call(ERROR_CODES, code);
|
||||
}
|
||||
|
||||
/** 에러 코드 정의를 조회한다. 미등록 코드는 폴백(SYS_001) 정의를 반환한다. */
|
||||
export function getErrorDefinition(code: string): ErrorCodeDefinition {
|
||||
return isErrorCode(code)
|
||||
? ERROR_CODES[code]
|
||||
: ERROR_CODES[FALLBACK_ERROR_CODE];
|
||||
}
|
||||
|
||||
/** HTTP 상태 코드에 대응하는 에러 코드를 찾는다. 4xx 는 BIZ_001, 그 외는 SYS_001 로 수렴한다. */
|
||||
export function resolveCodeByStatus(status: number): ErrorCode {
|
||||
const mapped = STATUS_TO_ERROR_CODE.get(status);
|
||||
if (mapped) return mapped;
|
||||
if (status >= 400 && status < 500) return 'BIZ_001';
|
||||
return FALLBACK_ERROR_CODE;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './error-codes';
|
||||
export * from './business.exception';
|
||||
@@ -0,0 +1,130 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
PayloadTooLargeException,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { HttpExceptionFilter } from './http-exception.filter';
|
||||
import { BusinessException } from '@/common/errors/business.exception';
|
||||
import { ERROR_CODES } from '@/common/errors/error-codes';
|
||||
|
||||
interface CapturedResponse {
|
||||
status: number;
|
||||
body: {
|
||||
success: boolean;
|
||||
error: { code: string; message: string; traceId?: string };
|
||||
};
|
||||
}
|
||||
|
||||
/** 필터 실행 후 실제로 내려간 응답을 캡처한다. */
|
||||
function runFilter(exception: unknown, requestId?: string): CapturedResponse {
|
||||
const captured = {} as CapturedResponse;
|
||||
|
||||
const response = {
|
||||
status(code: number) {
|
||||
captured.status = code;
|
||||
return this;
|
||||
},
|
||||
json(body: CapturedResponse['body']) {
|
||||
captured.body = body;
|
||||
return this;
|
||||
},
|
||||
};
|
||||
|
||||
const request = {
|
||||
method: 'GET',
|
||||
url: '/api/users/1',
|
||||
header: () => requestId,
|
||||
};
|
||||
|
||||
const host = {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => request,
|
||||
getResponse: () => response,
|
||||
}),
|
||||
} as unknown as ArgumentsHost;
|
||||
|
||||
new HttpExceptionFilter().catch(exception, host);
|
||||
return captured;
|
||||
}
|
||||
|
||||
describe('HttpExceptionFilter', () => {
|
||||
beforeAll(() => {
|
||||
// 의도된 예외 로그가 테스트 출력을 오염시키지 않도록 억제
|
||||
jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
|
||||
jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('BusinessException 은 지정한 코드와 상태를 그대로 내보낸다', () => {
|
||||
const result = runFilter(new BusinessException('RES_001'));
|
||||
|
||||
expect(result.status).toBe(HttpStatus.NOT_FOUND);
|
||||
expect(result.body).toEqual({
|
||||
success: false,
|
||||
error: { code: 'RES_001', message: ERROR_CODES.RES_001.message },
|
||||
});
|
||||
});
|
||||
|
||||
it('Nest 내장 예외는 상태 코드로 역매핑된다', () => {
|
||||
expect(runFilter(new NotFoundException()).body.error.code).toBe('RES_001');
|
||||
expect(runFilter(new ForbiddenException()).body.error.code).toBe(
|
||||
'AUTH_003',
|
||||
);
|
||||
expect(runFilter(new BadRequestException()).body.error.code).toBe(
|
||||
'VAL_001',
|
||||
);
|
||||
});
|
||||
|
||||
it('ValidationPipe 의 상세 사유(배열 message)는 노출하지 않는다', () => {
|
||||
const exception = new BadRequestException({
|
||||
message: ['email must be an email'],
|
||||
error: 'Bad Request',
|
||||
statusCode: 400,
|
||||
});
|
||||
|
||||
const result = runFilter(exception);
|
||||
|
||||
expect(result.body.error.code).toBe('VAL_001');
|
||||
expect(result.body.error.message).toBe(ERROR_CODES.VAL_001.message);
|
||||
});
|
||||
|
||||
it('라이브러리가 만든 영문 메시지를 사용자에게 노출하지 않는다', () => {
|
||||
// multer 는 크기 초과 시 "File too large" 라는 영문 메시지로 예외를 만든다.
|
||||
// 사용자 노출 문구는 에러 코드 사전에만 존재해야 한다.
|
||||
const result = runFilter(new PayloadTooLargeException('File too large'));
|
||||
|
||||
expect(result.status).toBe(HttpStatus.PAYLOAD_TOO_LARGE);
|
||||
expect(result.body.error.code).toBe('FILE_002');
|
||||
expect(result.body.error.message).toBe(ERROR_CODES.FILE_002.message);
|
||||
expect(JSON.stringify(result.body)).not.toContain('File too large');
|
||||
});
|
||||
|
||||
it('미정의 예외는 내부 정보 없이 SYS_001 로 수렴한다', () => {
|
||||
const result = runFilter(new Error('DB 커넥션 풀 고갈: host=10.0.0.5'));
|
||||
|
||||
expect(result.status).toBe(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
expect(result.body.error.code).toBe('SYS_001');
|
||||
expect(result.body.error.message).toBe(ERROR_CODES.SYS_001.message);
|
||||
expect(JSON.stringify(result.body)).not.toContain('10.0.0.5');
|
||||
});
|
||||
|
||||
it('요청 추적 ID 가 있으면 응답에 traceId 로 포함한다', () => {
|
||||
const result = runFilter(new BusinessException('SYS_001'), 'trace-abc');
|
||||
|
||||
expect(result.body.error.traceId).toBe('trace-abc');
|
||||
});
|
||||
|
||||
it('요청 추적 ID 가 없으면 traceId 키를 넣지 않는다', () => {
|
||||
const result = runFilter(new BusinessException('SYS_001'));
|
||||
|
||||
expect(result.body.error).not.toHaveProperty('traceId');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Request, Response } from 'express';
|
||||
|
||||
import { BusinessException } from '@/common/errors/business.exception';
|
||||
import {
|
||||
ErrorCode,
|
||||
FALLBACK_ERROR_CODE,
|
||||
getErrorDefinition,
|
||||
isErrorCode,
|
||||
resolveCodeByStatus,
|
||||
} from '@/common/errors/error-codes';
|
||||
import { REQUEST_ID_HEADER } from '@/common/middleware/request-id.middleware';
|
||||
|
||||
/** 이 값 이상이면 서버 책임 오류로 보고 error 레벨로 남긴다. */
|
||||
const SERVER_ERROR_STATUS_THRESHOLD = 500;
|
||||
|
||||
/**
|
||||
* 전역 Exception Filter — 모든 실패 응답을 표준 포맷으로 변환한다.
|
||||
* 에러 코드 ↔ 메시지 ↔ HTTP 상태는 error-codes.ts 레지스트리가 SSOT 이며,
|
||||
* 이 필터는 조회만 한다(여기에 문구를 하드코딩하지 말 것).
|
||||
*/
|
||||
@Catch()
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(HttpExceptionFilter.name);
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const ctx = host.switchToHttp();
|
||||
const request = ctx.getRequest<Request>();
|
||||
const response = ctx.getResponse<Response>();
|
||||
|
||||
const { status, code, message } = this.resolve(exception);
|
||||
const traceId = request.header(REQUEST_ID_HEADER) ?? undefined;
|
||||
|
||||
this.log(exception, status, code, request, traceId);
|
||||
|
||||
response.status(status).json({
|
||||
success: false,
|
||||
error: { code, message, ...(traceId ? { traceId } : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
/** 예외를 { status, code, message } 로 정규화한다. */
|
||||
private resolve(exception: unknown): {
|
||||
status: HttpStatus;
|
||||
code: ErrorCode;
|
||||
message: string;
|
||||
} {
|
||||
// 1. BusinessException — 코드가 이미 확정되어 있다.
|
||||
if (exception instanceof BusinessException) {
|
||||
const body = exception.getResponse() as {
|
||||
code: ErrorCode;
|
||||
message: string;
|
||||
};
|
||||
return {
|
||||
status: exception.getStatus(),
|
||||
code: body.code,
|
||||
message: body.message,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 그 외 HttpException(프레임워크/Nest 내장 예외) — 상태 코드로 역매핑한다.
|
||||
if (exception instanceof HttpException) {
|
||||
const status = exception.getStatus();
|
||||
const body = exception.getResponse();
|
||||
const explicitCode = this.extractCode(body);
|
||||
const code = explicitCode ?? resolveCodeByStatus(status);
|
||||
|
||||
return {
|
||||
status,
|
||||
code,
|
||||
// 프레임워크/라이브러리가 만든 영문 메시지("File too large" 등)가 그대로 새어나가지 않도록
|
||||
// **항상 레지스트리 문구**를 쓴다. 사용자 노출 문구를 재정의하려면 BusinessException 을 사용한다.
|
||||
message: getErrorDefinition(code).message,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 미정의 예외 — 내부 정보가 새지 않도록 항상 SYS_001 로 수렴시킨다.
|
||||
return {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
code: FALLBACK_ERROR_CODE,
|
||||
message: getErrorDefinition(FALLBACK_ERROR_CODE).message,
|
||||
};
|
||||
}
|
||||
|
||||
/** 예외 본문에 error code 가 실려 있으면 꺼낸다. */
|
||||
private extractCode(body: unknown): ErrorCode | null {
|
||||
if (typeof body === 'object' && body !== null && 'code' in body) {
|
||||
const code: unknown = body.code;
|
||||
if (typeof code === 'string' && isErrorCode(code)) return code;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 5xx 는 error, 4xx 는 warn 으로 남긴다. 추적을 위해 traceId 를 함께 기록한다. */
|
||||
private log(
|
||||
exception: unknown,
|
||||
status: number,
|
||||
code: ErrorCode,
|
||||
request: Request,
|
||||
traceId?: string,
|
||||
): void {
|
||||
const where = `${request.method} ${request.url}`;
|
||||
const prefix = `[${code}]${traceId ? `[${traceId}]` : ''} ${where}`;
|
||||
|
||||
if (status >= SERVER_ERROR_STATUS_THRESHOLD) {
|
||||
this.logger.error(
|
||||
prefix,
|
||||
exception instanceof Error ? exception.stack : String(exception),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const context =
|
||||
exception instanceof BusinessException && exception.context
|
||||
? ` ${JSON.stringify(exception.context)}`
|
||||
: '';
|
||||
this.logger.warn(`${prefix}${context}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
import { SKIP_TRANSFORM_KEY } from '@/common/decorators/skip-transform.decorator';
|
||||
|
||||
export interface StandardResponse<T> {
|
||||
success: true;
|
||||
// 핸들러가 undefined/null 을 반환하면 null 로 정규화되므로 nullable
|
||||
data: T | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 성공 응답을 { success: true, data } 로 래핑한다.
|
||||
* `@SkipTransform()` 이 붙은 핸들러는 원본 응답을 그대로 통과시킨다.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TransformInterceptor<T> implements NestInterceptor<
|
||||
T,
|
||||
StandardResponse<T> | T
|
||||
> {
|
||||
constructor(private readonly reflector: Reflector) {}
|
||||
|
||||
intercept(
|
||||
context: ExecutionContext,
|
||||
next: CallHandler,
|
||||
): Observable<StandardResponse<T> | T> {
|
||||
const skip = this.reflector.getAllAndOverride<boolean>(SKIP_TRANSFORM_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
const source = next.handle() as Observable<T>;
|
||||
if (skip) return source;
|
||||
|
||||
return source.pipe(
|
||||
map((data) => ({
|
||||
success: true as const,
|
||||
data: data ?? null,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Injectable, NestMiddleware } from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
|
||||
/** 요청 추적 헤더명 — 로그·에러 응답의 traceId 와 동일한 값을 사용한다. */
|
||||
export const REQUEST_ID_HEADER = 'x-request-id';
|
||||
|
||||
/**
|
||||
* 요청 추적 ID 미들웨어.
|
||||
* 프록시/클라이언트가 보낸 값이 있으면 이어받고, 없으면 새로 발급한다.
|
||||
* 발급된 ID 는 응답 헤더로도 돌려주어 클라이언트가 문의 시 제시할 수 있게 한다.
|
||||
*/
|
||||
@Injectable()
|
||||
export class RequestIdMiddleware implements NestMiddleware {
|
||||
use(req: Request, res: Response, next: NextFunction): void {
|
||||
const incoming = req.header(REQUEST_ID_HEADER);
|
||||
const requestId =
|
||||
incoming && incoming.trim() !== '' ? incoming : randomUUID();
|
||||
|
||||
req.headers[REQUEST_ID_HEADER] = requestId;
|
||||
res.setHeader(REQUEST_ID_HEADER, requestId);
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import 'reflect-metadata';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
import { buildDatabaseOptions } from '@/shared/config/database.config';
|
||||
|
||||
/**
|
||||
* TypeORM CLI 전용 DataSource.
|
||||
*
|
||||
* 앱 런타임은 app.module.ts 의 TypeOrmModule 을 사용하고,
|
||||
* 이 파일은 `migration:generate` / `migration:run` 같은 CLI 명령에만 쓰인다.
|
||||
* 접속 설정은 database.config.ts 를 공유하므로 두 경로가 어긋나지 않는다.
|
||||
*
|
||||
* ⚠️ DB 접속 정보(DB_*)는 루트 .env 에서 docker-compose 가 주입하므로,
|
||||
* 마이그레이션 명령은 **컨테이너 안에서** 실행해야 한다.
|
||||
* 자세한 절차는 .claude/skills/nestjs/SKILL.md 의 "DB 마이그레이션" 참조.
|
||||
*/
|
||||
export default new DataSource(buildDatabaseOptions());
|
||||
@@ -0,0 +1,109 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { Logger, RequestMethod, ValidationPipe } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { WinstonModule } from 'nest-winston';
|
||||
import helmet from 'helmet';
|
||||
import type {
|
||||
Express,
|
||||
Request as ExpressRequest,
|
||||
Response as ExpressResponse,
|
||||
} from 'express';
|
||||
|
||||
import { Reflector } from '@nestjs/core';
|
||||
|
||||
import { HttpExceptionFilter } from '@/common/filters/http-exception.filter';
|
||||
import { TransformInterceptor } from '@/common/interceptors/transform.interceptor';
|
||||
import { winstonConfig } from '@/shared/logger/winston.config';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
logger: WinstonModule.createLogger(winstonConfig),
|
||||
});
|
||||
|
||||
// 리버스 프록시(Nginx, Docker 배포 환경 등) 뒤에서 올바른 클라이언트 IP 식별 지원을 위해 설정합니다.
|
||||
const expressApp = app.getHttpAdapter().getInstance() as Express;
|
||||
expressApp.set('trust proxy', 1);
|
||||
|
||||
// 글로벌 prefix — 모든 라우트가 /api/* 로 정규화됨 (Flutter, Web 양쪽 baseURL과 일치)
|
||||
app.setGlobalPrefix('api', {
|
||||
// 헬스체크 / 루트 상태 엔드포인트는 prefix 미적용
|
||||
exclude: [{ path: '/', method: RequestMethod.GET }],
|
||||
});
|
||||
|
||||
// 기본 주소('/') 접속 시 상태 확인용 텍스트 응답 추가
|
||||
expressApp.get('/', (_req: ExpressRequest, res: ExpressResponse) => {
|
||||
res.send('Backend API Server is running 정상 구동 중입니다.');
|
||||
});
|
||||
|
||||
// 1. 보안 헤더 (Helmet) - XSS 방지 및 기본 웹 보안
|
||||
app.use(helmet());
|
||||
|
||||
// 2. 화이트리스트 기반 CORS 정책
|
||||
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
|
||||
const corsOriginEnv = process.env.CORS_ORIGIN;
|
||||
|
||||
app.enableCors({
|
||||
origin: (
|
||||
origin: string | undefined,
|
||||
callback: (err: Error | null, allow?: boolean) => void,
|
||||
) => {
|
||||
// 서버간의 통신(origin이 undefined)이거나 명시된 리스트일 때만 허용
|
||||
const whitelist = [frontendUrl, 'http://localhost:3000'];
|
||||
if (corsOriginEnv) whitelist.push(corsOriginEnv);
|
||||
|
||||
if (!origin || whitelist.indexOf(origin) !== -1) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
// Error 를 넘기면 500(SYS_001)이 되어 원인 파악이 어려우므로,
|
||||
// CORS 헤더를 부여하지 않아 브라우저가 차단하도록 한다.
|
||||
callback(null, false);
|
||||
}
|
||||
},
|
||||
credentials: true, // 쿠키 교환 허용
|
||||
});
|
||||
|
||||
// 3. Rate Limiting 은 AppModule 의 ThrottlerGuard(APP_GUARD)로 일원화되어 있다.
|
||||
// 라우트 단위 제어(@Throttle / @SkipThrottle)가 가능하고, 한도 초과는 REQ_001(429)로 응답된다.
|
||||
// (전역 예외 필터가 429 → REQ_001 로 매핑한다 — .claude/rules/error-codes.md)
|
||||
|
||||
// 4. 전역 DTO 유효성 파이프 (강력한 검증 단계)
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true, // DTO에 불필요한 값이 오면 삭제
|
||||
forbidNonWhitelisted: true, // DTO에 없는 필드가 주입되면 400 에러 발생
|
||||
transform: true, // 네트워크 데이터를 DTO나 기본 타입으로 자동 변환
|
||||
}),
|
||||
);
|
||||
|
||||
// 5. 프론트엔드 연동을 위한 규격화된 에러 & 성공 페이로드 인터셉터 적용
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
app.useGlobalInterceptors(new TransformInterceptor(app.get(Reflector)));
|
||||
|
||||
// 6. Swagger API 문서 설정
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('Backend API Documentation')
|
||||
.setDescription('The API documentation conforming to the global guidelines')
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api-docs', app, document);
|
||||
|
||||
// 7. Graceful shutdown — SIGTERM 수신 시 새 요청을 받지 않고
|
||||
// 처리 중인 요청을 마친 뒤 DB/Redis 커넥션을 정리하고 종료한다.
|
||||
// (이 설정이 없으면 배포·재시작 때 처리 중이던 요청이 그대로 끊긴다)
|
||||
app.enableShutdownHooks();
|
||||
|
||||
// 종료 로그는 ShutdownLogger(OnApplicationShutdown)가 남긴다.
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
await app.listen(port, '0.0.0.0');
|
||||
Logger.log(`🚀 Backend running on http://localhost:${port}/api`, 'Bootstrap');
|
||||
Logger.log(
|
||||
`📘 Swagger docs at http://localhost:${port}/api-docs`,
|
||||
'Bootstrap',
|
||||
);
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
@@ -0,0 +1,84 @@
|
||||
import { HttpStatus, ServiceUnavailableException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import {
|
||||
HealthCheckResult,
|
||||
HealthCheckService,
|
||||
TypeOrmHealthIndicator,
|
||||
} from '@nestjs/terminus';
|
||||
import { Response } from 'express';
|
||||
|
||||
import { HealthController } from './health.controller';
|
||||
import { SKIP_TRANSFORM_KEY } from '@/common/decorators/skip-transform.decorator';
|
||||
|
||||
const okResult = {
|
||||
status: 'ok',
|
||||
info: { database: { status: 'up' } },
|
||||
error: {},
|
||||
details: { database: { status: 'up' } },
|
||||
} as unknown as HealthCheckResult;
|
||||
|
||||
const downResult = {
|
||||
status: 'error',
|
||||
info: {},
|
||||
error: { database: { status: 'down', message: 'timeout' } },
|
||||
details: { database: { status: 'down', message: 'timeout' } },
|
||||
};
|
||||
|
||||
describe('HealthController', () => {
|
||||
let controller: HealthController;
|
||||
let check: jest.Mock;
|
||||
let res: { status: jest.Mock };
|
||||
|
||||
beforeEach(async () => {
|
||||
check = jest.fn();
|
||||
res = { status: jest.fn() };
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [HealthController],
|
||||
providers: [
|
||||
{ provide: HealthCheckService, useValue: { check } },
|
||||
{ provide: TypeOrmHealthIndicator, useValue: { pingCheck: jest.fn() } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get(HealthController);
|
||||
});
|
||||
|
||||
it('헬스체크는 표준 응답 래핑에서 제외된다 (모니터링 도구가 원본 형식을 읽는다)', () => {
|
||||
// SkipTransform 메타데이터가 컨트롤러에 붙어 있어야 인터셉터가 래핑을 건너뛴다
|
||||
const skip: unknown = Reflect.getMetadata(
|
||||
SKIP_TRANSFORM_KEY,
|
||||
HealthController,
|
||||
);
|
||||
expect(skip).toBe(true);
|
||||
});
|
||||
|
||||
it('정상이면 terminus 결과를 그대로 반환한다', async () => {
|
||||
check.mockResolvedValue(okResult);
|
||||
|
||||
const result = await controller.check(res as unknown as Response);
|
||||
|
||||
expect(result).toEqual(okResult);
|
||||
// 성공 시에는 상태 코드를 건드리지 않는다
|
||||
expect(res.status).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('실패하면 503 과 함께 어느 구성요소가 죽었는지 그대로 노출한다', async () => {
|
||||
check.mockRejectedValue(new ServiceUnavailableException(downResult));
|
||||
|
||||
const result = await controller.check(res as unknown as Response);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(HttpStatus.SERVICE_UNAVAILABLE);
|
||||
// SYS_001 로 덮어쓰지 않고 원인을 유지해야 한다
|
||||
expect(result).toEqual(downResult);
|
||||
expect(JSON.stringify(result)).toContain('database');
|
||||
});
|
||||
|
||||
it('terminus 예외가 아닌 오류는 전역 필터로 넘긴다', async () => {
|
||||
check.mockRejectedValue(new Error('예상치 못한 오류'));
|
||||
|
||||
await expect(controller.check(res as unknown as Response)).rejects.toThrow(
|
||||
'예상치 못한 오류',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
HttpStatus,
|
||||
Res,
|
||||
ServiceUnavailableException,
|
||||
} from '@nestjs/common';
|
||||
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { SkipThrottle } from '@nestjs/throttler';
|
||||
import {
|
||||
HealthCheck,
|
||||
HealthCheckResult,
|
||||
HealthCheckService,
|
||||
TypeOrmHealthIndicator,
|
||||
} from '@nestjs/terminus';
|
||||
import type { Response } from 'express';
|
||||
|
||||
import { SkipTransform } from '@/common/decorators/skip-transform.decorator';
|
||||
|
||||
// DB ping 타임아웃 — 기본값 1000ms 는 너무 짧다.
|
||||
// 커넥션 풀의 유휴 커넥션이 정리된 뒤(idleTimeoutMillis) 재연결하는 경우 1초를 넘겨
|
||||
// 정상인 DB 를 down 으로 오판하고 헬스체크가 간헐적으로 실패한다.
|
||||
const DB_PING_TIMEOUT_MS = 5_000;
|
||||
|
||||
/**
|
||||
* 헬스체크 엔드포인트 — Docker healthcheck, 모니터링 시스템이 읽는다.
|
||||
*
|
||||
* 이 엔드포인트는 **사람이 아니라 기계가 소비**하므로 표준 응답 래퍼와 에러 코드 규칙에서 제외한다.
|
||||
* (`{success,data}` 로 감싸거나 실패를 SYS_001 로 덮어쓰면 "어느 컴포넌트가 죽었는지"가 사라진다)
|
||||
*
|
||||
* - 성공 200: `{ status: 'ok', info: { database: { status: 'up' } }, ... }`
|
||||
* - 실패 503: `{ status: 'error', error: { database: { status: 'down', message } }, ... }`
|
||||
*
|
||||
* 주기적으로 호출되므로 rate limit 대상에서도 제외한다 (한도를 소진시켜 실제 요청을 막으면 안 된다).
|
||||
*/
|
||||
@SkipThrottle()
|
||||
@SkipTransform()
|
||||
@ApiTags('Health')
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(
|
||||
private readonly health: HealthCheckService,
|
||||
private readonly db: TypeOrmHealthIndicator,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@HealthCheck()
|
||||
@ApiOperation({
|
||||
summary: '애플리케이션 상태 확인 (표준 응답 래퍼 미적용)',
|
||||
})
|
||||
@ApiResponse({ status: 200, description: '모든 구성요소 정상' })
|
||||
@ApiResponse({
|
||||
status: 503,
|
||||
description: '하나 이상의 구성요소 비정상 — 본문의 error 에 원인이 담긴다',
|
||||
})
|
||||
async check(
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
): Promise<HealthCheckResult> {
|
||||
try {
|
||||
return await this.health.check([
|
||||
() => this.db.pingCheck('database', { timeout: DB_PING_TIMEOUT_MS }),
|
||||
]);
|
||||
} catch (error) {
|
||||
// terminus 는 실패 시 ServiceUnavailableException 을 던지며 본문에 상세 결과를 담는다.
|
||||
// 전역 필터가 SYS_001 로 덮어쓰지 않도록 여기서 직접 503 과 원본 본문을 반환한다.
|
||||
if (error instanceof ServiceUnavailableException) {
|
||||
res.status(HttpStatus.SERVICE_UNAVAILABLE);
|
||||
return error.getResponse() as HealthCheckResult;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TerminusModule } from '@nestjs/terminus';
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
imports: [TerminusModule],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
/** 업로드 결과 — 저장 경로(절대경로)는 노출하지 않는다 */
|
||||
export class UploadResponseDto {
|
||||
@ApiProperty({
|
||||
description: '서버가 생성한 파일 식별자 (저장 파일명)',
|
||||
example: 'b1f0c2e4-8a3d-4c7e-9f21-0d5a6b7c8e9f.png',
|
||||
})
|
||||
fileName!: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: '업로드 당시 원본 파일명',
|
||||
example: '프로필.png',
|
||||
})
|
||||
originalName!: string;
|
||||
|
||||
@ApiProperty({ description: 'MIME 타입', example: 'image/png' })
|
||||
mimeType!: string;
|
||||
|
||||
@ApiProperty({ description: '파일 크기 (바이트)', example: 20480 })
|
||||
size!: number;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { allowedExtensionList, isAllowedFile } from './upload.config';
|
||||
|
||||
describe('파일 업로드 검증', () => {
|
||||
it('확장자와 MIME 이 모두 맞으면 통과한다', () => {
|
||||
expect(isAllowedFile('photo.png', 'image/png')).toBe(true);
|
||||
expect(isAllowedFile('scan.PDF', 'application/pdf')).toBe(true);
|
||||
});
|
||||
|
||||
it('허용되지 않은 MIME 은 거부한다', () => {
|
||||
expect(isAllowedFile('script.js', 'application/javascript')).toBe(false);
|
||||
expect(isAllowedFile('page.html', 'text/html')).toBe(false);
|
||||
});
|
||||
|
||||
it('MIME 은 허용이지만 확장자가 불일치하면 거부한다 (확장자 위장 방지)', () => {
|
||||
expect(isAllowedFile('payload.html', 'image/png')).toBe(false);
|
||||
expect(isAllowedFile('payload.exe', 'application/pdf')).toBe(false);
|
||||
});
|
||||
|
||||
it('확장자가 없으면 거부한다', () => {
|
||||
expect(isAllowedFile('nofile', 'image/png')).toBe(false);
|
||||
});
|
||||
|
||||
it('실행 가능한 형식은 허용 목록에 없다', () => {
|
||||
const allowed = allowedExtensionList();
|
||||
|
||||
for (const dangerous of ['.html', '.svg', '.js', '.exe', '.sh']) {
|
||||
expect(allowed).not.toContain(dangerous);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { extname } from 'path';
|
||||
|
||||
import { parsePositiveInt } from '@/shared/utils/env';
|
||||
|
||||
/**
|
||||
* 파일 업로드 정책 (로컬 디스크 기준).
|
||||
*
|
||||
* 오브젝트 스토리지(S3 등)로 전환할 때는 저장 어댑터만 교체하고
|
||||
* 검증 규칙(허용 형식·크기)은 그대로 재사용한다.
|
||||
*/
|
||||
|
||||
/** 업로드 파일 저장 디렉터리 — 컨테이너에서는 compose 볼륨이 연결된다 */
|
||||
export const UPLOAD_DIR = process.env.UPLOAD_DIR ?? './uploads';
|
||||
|
||||
const MEGABYTE = 1024 * 1024;
|
||||
|
||||
/** 파일 1개 최대 크기 (기본 5MB) */
|
||||
export const MAX_FILE_SIZE_BYTES =
|
||||
parsePositiveInt(process.env.UPLOAD_MAX_SIZE_MB, 5) * MEGABYTE;
|
||||
|
||||
/**
|
||||
* 허용 형식 — 확장자와 MIME 타입을 **둘 다** 검사한다.
|
||||
* 확장자만 보면 위장이 쉽고, MIME 만 보면 클라이언트가 보낸 값이라 신뢰할 수 없다.
|
||||
*
|
||||
* ⚠️ 실행 가능한 형식(.html, .svg, .js 등)은 넣지 말 것 —
|
||||
* 저장된 파일을 그대로 서빙할 경우 XSS 로 이어진다.
|
||||
*/
|
||||
export const ALLOWED_FILE_TYPES: ReadonlyMap<string, readonly string[]> =
|
||||
new Map([
|
||||
['image/jpeg', ['.jpg', '.jpeg']],
|
||||
['image/png', ['.png']],
|
||||
['image/webp', ['.webp']],
|
||||
['image/gif', ['.gif']],
|
||||
['application/pdf', ['.pdf']],
|
||||
]);
|
||||
|
||||
/** 허용 형식인지 검사한다 (확장자 ↔ MIME 조합이 일치해야 통과) */
|
||||
export function isAllowedFile(originalName: string, mimeType: string): boolean {
|
||||
const allowedExtensions = ALLOWED_FILE_TYPES.get(mimeType);
|
||||
if (!allowedExtensions) return false;
|
||||
|
||||
return allowedExtensions.includes(extname(originalName).toLowerCase());
|
||||
}
|
||||
|
||||
/** 사용자에게 안내할 허용 확장자 목록 */
|
||||
export function allowedExtensionList(): string {
|
||||
return [...ALLOWED_FILE_TYPES.values()].flat().join(', ');
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBody, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import {
|
||||
ApiErrorResponse,
|
||||
ApiStandardResponse,
|
||||
} from '@/common/decorators/api-standard-response.decorator';
|
||||
import { BusinessException } from '@/common/errors/business.exception';
|
||||
import { UploadResponseDto } from './dto/upload-response.dto';
|
||||
import { UploadService } from './upload.service';
|
||||
|
||||
// 파일 업로드 샘플 — 새 업로드 엔드포인트는 이 패턴을 복제한다.
|
||||
// 검증(형식·크기)과 안전한 파일명 생성은 UploadModule 의 multer 설정이 담당한다.
|
||||
@ApiTags('Upload')
|
||||
@Controller('files')
|
||||
export class UploadController {
|
||||
constructor(private readonly uploadService: UploadService) {}
|
||||
|
||||
@Post()
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
@ApiOperation({ summary: '파일 업로드 (단일)' })
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@ApiBody({
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
file: { type: 'string', format: 'binary' },
|
||||
},
|
||||
required: ['file'],
|
||||
},
|
||||
})
|
||||
@ApiStandardResponse(UploadResponseDto, {
|
||||
status: 201,
|
||||
description: '업로드 성공',
|
||||
})
|
||||
@ApiErrorResponse('FILE_001', '허용되지 않는 파일 형식')
|
||||
@ApiErrorResponse('FILE_002', '파일 크기 초과')
|
||||
upload(@UploadedFile() file?: Express.Multer.File): UploadResponseDto {
|
||||
if (!file) {
|
||||
// 파일 없이 요청한 경우 — multer 는 오류를 내지 않으므로 여기서 막는다
|
||||
throw new BusinessException('VAL_001', {
|
||||
message: '업로드할 파일을 선택해 주세요.',
|
||||
});
|
||||
}
|
||||
|
||||
return this.uploadService.toResponse(file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MulterModule } from '@nestjs/platform-express';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { diskStorage } from 'multer';
|
||||
import { mkdirSync } from 'fs';
|
||||
import { extname } from 'path';
|
||||
|
||||
import { BusinessException } from '@/common/errors/business.exception';
|
||||
import {
|
||||
MAX_FILE_SIZE_BYTES,
|
||||
UPLOAD_DIR,
|
||||
isAllowedFile,
|
||||
} from './upload.config';
|
||||
import { UploadController } from './upload.controller';
|
||||
import { UploadService } from './upload.service';
|
||||
|
||||
// 저장 디렉터리는 기동 시 한 번 보장한다 (없으면 multer 가 매 요청 실패한다)
|
||||
mkdirSync(UPLOAD_DIR, { recursive: true });
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MulterModule.register({
|
||||
storage: diskStorage({
|
||||
destination: UPLOAD_DIR,
|
||||
filename: (_req, file, callback) => {
|
||||
// ⚠️ 클라이언트가 보낸 파일명을 경로에 쓰지 않는다.
|
||||
// '../../etc/passwd' 같은 값이 그대로 들어오면 경로 탈출이 된다.
|
||||
// 서버가 생성한 UUID + 검증된 확장자만 사용한다.
|
||||
const safeExtension = extname(file.originalname).toLowerCase();
|
||||
callback(null, `${randomUUID()}${safeExtension}`);
|
||||
},
|
||||
}),
|
||||
limits: {
|
||||
fileSize: MAX_FILE_SIZE_BYTES,
|
||||
// 파일 외 필드 수를 제한해 과도한 파싱을 막는다
|
||||
files: 1,
|
||||
fields: 10,
|
||||
},
|
||||
fileFilter: (_req, file, callback) => {
|
||||
if (!isAllowedFile(file.originalname, file.mimetype)) {
|
||||
// 에러 코드와 함께 거부한다 (전역 필터가 표준 응답으로 변환)
|
||||
callback(new BusinessException('FILE_001'), false);
|
||||
return;
|
||||
}
|
||||
callback(null, true);
|
||||
},
|
||||
}),
|
||||
],
|
||||
controllers: [UploadController],
|
||||
providers: [UploadService],
|
||||
exports: [UploadService],
|
||||
})
|
||||
export class UploadModule {}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { unlink } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
|
||||
import { UPLOAD_DIR } from './upload.config';
|
||||
import { UploadResponseDto } from './dto/upload-response.dto';
|
||||
|
||||
// 업로드된 파일의 메타데이터를 다루는 계층.
|
||||
// 저장 자체는 multer(diskStorage)가 수행하며, 여기서는 그 결과를 정리한다.
|
||||
@Injectable()
|
||||
export class UploadService {
|
||||
private readonly logger = new Logger(UploadService.name);
|
||||
|
||||
/** multer 가 저장한 파일 정보를 응답 DTO 로 변환한다 */
|
||||
toResponse(file: Express.Multer.File): UploadResponseDto {
|
||||
this.logger.log(
|
||||
`파일 업로드 완료: ${file.filename} (${file.size} bytes, ${file.mimetype})`,
|
||||
);
|
||||
|
||||
return {
|
||||
fileName: file.filename,
|
||||
// 원본 파일명은 표시용 메타데이터일 뿐이며 경로 조립에 사용하지 않는다
|
||||
originalName: file.originalname,
|
||||
mimeType: file.mimetype,
|
||||
size: file.size,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 저장된 파일을 삭제한다.
|
||||
* 파일명은 서버가 생성한 값만 받아야 한다 — 외부 입력을 그대로 넘기면 경로 탈출 위험이 있다.
|
||||
*/
|
||||
async remove(fileName: string): Promise<void> {
|
||||
await unlink(join(UPLOAD_DIR, fileName));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
// 사용자 생성 DTO 샘플 — 모든 검증 메시지는 한국어, Swagger 메타 필수
|
||||
export class CreateUserDto {
|
||||
@ApiProperty({ description: '사용자 이메일', example: 'user@example.com' })
|
||||
@IsEmail({}, { message: '올바른 이메일 형식을 입력해 주세요.' })
|
||||
@IsNotEmpty({ message: '이메일은 필수 입력 항목입니다.' })
|
||||
email!: string;
|
||||
|
||||
@ApiProperty({ description: '비밀번호 (최소 8자)', example: 'password123' })
|
||||
@IsString()
|
||||
@MinLength(8, { message: '비밀번호는 최소 8자 이상이어야 합니다.' })
|
||||
password!: string;
|
||||
|
||||
@ApiProperty({ description: '사용자 이름', example: '홍길동' })
|
||||
@IsString()
|
||||
@IsNotEmpty({ message: '이름은 필수 입력 항목입니다.' })
|
||||
name!: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
/** 사용자 응답 DTO — Swagger 스키마와 클라이언트 타입의 기준이 된다. */
|
||||
export class UserResponseDto {
|
||||
@ApiProperty({ description: '사용자 ID', example: 1 })
|
||||
id!: number;
|
||||
|
||||
@ApiProperty({ description: '사용자 이메일', example: 'user@example.com' })
|
||||
email!: string;
|
||||
|
||||
@ApiProperty({ description: '사용자 이름', example: '홍길동' })
|
||||
name!: string;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Post,
|
||||
Query,
|
||||
} from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
|
||||
import {
|
||||
ApiErrorResponse,
|
||||
ApiStandardResponse,
|
||||
} from '@/common/decorators/api-standard-response.decorator';
|
||||
import { CursorPaginationQueryDto } from '@/common/dto/pagination.dto';
|
||||
import { UserService } from './user.service';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UserResponseDto } from './dto/user-response.dto';
|
||||
|
||||
// 사용자 도메인 컨트롤러 샘플 — 라우팅과 입출력만 담당, 비즈니스 로직은 모두 service 위임
|
||||
@ApiTags('User')
|
||||
@ApiBearerAuth()
|
||||
@Controller('users')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '사용자 목록 조회 (커서 페이지네이션)' })
|
||||
@ApiStandardResponse(UserResponseDto, {
|
||||
status: 200,
|
||||
description: '사용자 목록 조회 성공',
|
||||
isArray: true,
|
||||
})
|
||||
@ApiErrorResponse('VAL_001', '페이지네이션 파라미터 오류')
|
||||
findMany(@Query() query: CursorPaginationQueryDto) {
|
||||
return this.userService.findMany(query.limit, query.cursor);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: '사용자 단건 조회' })
|
||||
@ApiStandardResponse(UserResponseDto, { description: '사용자 조회 성공' })
|
||||
@ApiErrorResponse('RES_001', '사용자를 찾을 수 없음')
|
||||
findOne(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.userService.findOne(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: '사용자 생성' })
|
||||
@ApiStandardResponse(UserResponseDto, {
|
||||
status: 201,
|
||||
description: '사용자 생성 성공',
|
||||
})
|
||||
@ApiErrorResponse('VAL_001', '입력값 검증 실패')
|
||||
@ApiErrorResponse('BIZ_001', '이메일 중복 등 비즈니스 규칙 위반')
|
||||
create(@Body() dto: CreateUserDto) {
|
||||
return this.userService.create(dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserController } from './user.controller';
|
||||
import { UserService } from './user.service';
|
||||
|
||||
@Module({
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
exports: [UserService],
|
||||
})
|
||||
export class UserModule {}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { BusinessException } from '@/common/errors/business.exception';
|
||||
import {
|
||||
PaginatedResult,
|
||||
toPaginatedResult,
|
||||
} from '@/common/dto/pagination.dto';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UserResponseDto } from './dto/user-response.dto';
|
||||
|
||||
// 비즈니스 로직 계층 샘플 — 실제 구현 시 Repository 주입하여 데이터 접근
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
// 임시 인메모리 저장소 — TypeORM Repository 도입 시 교체
|
||||
private readonly users = new Map<number, UserResponseDto>();
|
||||
|
||||
findOne(id: number): UserResponseDto {
|
||||
const user = this.users.get(id);
|
||||
if (!user) {
|
||||
// 사용자 노출 실패는 항상 에러 코드와 함께 던진다.
|
||||
throw new BusinessException('RES_001', { context: { userId: id } });
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/** 커서 기반 목록 조회 샘플 — 목록 API 는 항상 페이지네이션을 적용한다. */
|
||||
findMany(limit: number, cursor?: string): PaginatedResult<UserResponseDto> {
|
||||
const afterId = cursor ? Number(cursor) : 0;
|
||||
const sorted = [...this.users.values()].sort((a, b) => a.id - b.id);
|
||||
const page = sorted.filter((user) => user.id > afterId).slice(0, limit);
|
||||
const last = page.at(-1);
|
||||
const hasNext = last ? sorted.some((user) => user.id > last.id) : false;
|
||||
|
||||
return toPaginatedResult(page, {
|
||||
hasNext,
|
||||
nextCursor: hasNext && last ? String(last.id) : null,
|
||||
total: sorted.length,
|
||||
});
|
||||
}
|
||||
|
||||
create(dto: CreateUserDto): UserResponseDto {
|
||||
const duplicated = [...this.users.values()].some(
|
||||
(user) => user.email === dto.email,
|
||||
);
|
||||
if (duplicated) {
|
||||
// 도메인 고유 코드가 필요하면 error-codes.ts 의 DOMAIN_ERROR_CODES 에 등록 후 사용한다.
|
||||
throw new BusinessException('BIZ_001', {
|
||||
message: '이미 가입된 이메일입니다. 다른 이메일을 사용해 주세요.',
|
||||
context: { email: dto.email },
|
||||
});
|
||||
}
|
||||
|
||||
const id = this.users.size + 1;
|
||||
const user: UserResponseDto = { id, email: dto.email, name: dto.name };
|
||||
this.users.set(id, user);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { join } from 'path';
|
||||
import { DataSourceOptions } from 'typeorm';
|
||||
|
||||
import { parsePositiveInt } from '@/shared/utils/env';
|
||||
|
||||
/**
|
||||
* DB 접속 설정 — 앱(TypeOrmModule)과 CLI(data-source.ts)가 **같은 설정을 공유**한다.
|
||||
* 두 곳에 따로 적으면 반드시 어긋나므로 여기서만 정의한다.
|
||||
*/
|
||||
|
||||
// 개발 환경 기본값 — **호스트에서 직접 실행할 때** 기준이다.
|
||||
// docker 환경에서는 compose 가 DB_HOST=db 등을 항상 주입하므로 이 값들이 쓰이지 않고,
|
||||
// 운영에서는 validateEnv 가 DB_* 를 필수로 요구한다.
|
||||
const DEV_DB_DEFAULTS = {
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
username: 'postgres',
|
||||
password: 'postgres',
|
||||
database: 'project_db',
|
||||
} as const;
|
||||
|
||||
/** 커넥션 풀 설정 */
|
||||
const POOL_OPTIONS = {
|
||||
max: 100,
|
||||
connectionTimeoutMillis: 5000,
|
||||
idleTimeoutMillis: 30000,
|
||||
} as const;
|
||||
|
||||
export function isProductionEnv(): boolean {
|
||||
return process.env.NODE_ENV === 'production';
|
||||
}
|
||||
|
||||
/**
|
||||
* 스키마 자동 동기화 사용 여부.
|
||||
*
|
||||
* **기본값은 false** 다. synchronize 를 켜두면 개발 DB 가 항상 최신 스키마와 일치해
|
||||
* `migration:generate` 가 "변경 없음"만 내놓는다. 그 상태로 운영에 배포하면
|
||||
* (운영은 synchronize 가 꺼져 있고 실행할 마이그레이션도 없어) 테이블이 만들어지지 않는다.
|
||||
*
|
||||
* 스키마 변경은 마이그레이션으로 관리한다 — 개발/운영이 같은 경로를 쓰게 된다.
|
||||
* 엔티티를 빠르게 실험할 때만 `DB_SYNCHRONIZE=true` 로 임시 활성화한다(개발 환경 한정).
|
||||
*/
|
||||
function shouldSynchronize(): boolean {
|
||||
// 운영에서는 어떤 값을 주더라도 절대 허용하지 않는다 (스키마 자동 변경 → 데이터 손실 위험)
|
||||
if (isProductionEnv()) return false;
|
||||
return process.env.DB_SYNCHRONIZE === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* 엔티티·마이그레이션 파일 경로.
|
||||
* `__dirname` 기준이라 ts-node(src)와 빌드 산출물(dist) 양쪽에서 동작한다.
|
||||
*/
|
||||
function resolvePaths(baseDir: string) {
|
||||
return {
|
||||
entities: [join(baseDir, '..', '..', '**', '*.entity{.ts,.js}')],
|
||||
migrations: [join(baseDir, '..', '..', 'migrations', '*{.ts,.js}')],
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDatabaseOptions(): DataSourceOptions {
|
||||
const isProduction = isProductionEnv();
|
||||
const paths = resolvePaths(__dirname);
|
||||
|
||||
return {
|
||||
type: 'postgres',
|
||||
host: process.env.DB_HOST ?? DEV_DB_DEFAULTS.host,
|
||||
port: parsePositiveInt(process.env.DB_PORT, DEV_DB_DEFAULTS.port),
|
||||
username: process.env.DB_USER ?? DEV_DB_DEFAULTS.username,
|
||||
password: process.env.DB_PASSWORD ?? DEV_DB_DEFAULTS.password,
|
||||
database: process.env.DB_NAME ?? DEV_DB_DEFAULTS.database,
|
||||
synchronize: shouldSynchronize(),
|
||||
// 운영 배포 시 미적용 마이그레이션을 자동 실행한다
|
||||
migrationsRun: isProduction,
|
||||
logging: !isProduction,
|
||||
extra: { ...POOL_OPTIONS },
|
||||
entities: paths.entities,
|
||||
migrations: paths.migrations,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { validateEnv } from './env.validation';
|
||||
|
||||
/** 지정한 키를 제외한 복사본 (구조분해로 버리면 lint 의 no-unused-vars 에 걸린다) */
|
||||
const omit = (source: Record<string, string>, ...keys: string[]) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(source).filter(([key]) => !keys.includes(key)),
|
||||
);
|
||||
|
||||
const prod = (extra: Record<string, string> = {}) => ({
|
||||
NODE_ENV: 'production',
|
||||
DB_HOST: 'db',
|
||||
DB_USER: 'app_user',
|
||||
DB_PASSWORD: 'a-real-secret',
|
||||
DB_NAME: 'project_db',
|
||||
...extra,
|
||||
});
|
||||
|
||||
describe('validateEnv', () => {
|
||||
describe('개발 환경', () => {
|
||||
it('DB 설정이 없어도 통과한다 (코드 기본값 사용)', () => {
|
||||
expect(() => validateEnv({ NODE_ENV: 'development' })).not.toThrow();
|
||||
});
|
||||
|
||||
it('숫자 항목이 잘못되면 환경과 무관하게 실패한다', () => {
|
||||
expect(() =>
|
||||
validateEnv({ NODE_ENV: 'development', PORT: 'abc' }),
|
||||
).toThrow(/PORT 는 양의 정수/);
|
||||
});
|
||||
|
||||
it('빈 문자열은 통과한다 (compose 가 미정의 변수를 빈 값으로 주입한다)', () => {
|
||||
expect(() =>
|
||||
validateEnv({ NODE_ENV: 'development', THROTTLE_LIMIT: '' }),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('운영 환경', () => {
|
||||
it('정상 설정이면 통과한다', () => {
|
||||
expect(() => validateEnv(prod())).not.toThrow();
|
||||
});
|
||||
|
||||
it('필수 DB 설정이 없으면 실패한다', () => {
|
||||
expect(() => validateEnv(omit(prod(), 'DB_PASSWORD'))).toThrow(
|
||||
/DB_PASSWORD 가 설정되지 않았습니다/,
|
||||
);
|
||||
});
|
||||
|
||||
it('예시 placeholder 가 그대로면 실패한다', () => {
|
||||
expect(() =>
|
||||
validateEnv(prod({ DB_PASSWORD: 'CHANGE-ME-BEFORE-DEPLOY' })),
|
||||
).toThrow(/DB_PASSWORD 가 예시 값 그대로입니다/);
|
||||
|
||||
expect(() =>
|
||||
validateEnv(prod({ JWT_SECRET: 'change-me-please' })),
|
||||
).toThrow(/JWT_SECRET 가 예시 값 그대로입니다/);
|
||||
});
|
||||
|
||||
it('약한 기본값(password)도 placeholder 로 간주한다', () => {
|
||||
expect(() => validateEnv(prod({ DB_PASSWORD: 'password' }))).toThrow(
|
||||
/예시 값 그대로/,
|
||||
);
|
||||
});
|
||||
|
||||
it('공개 주소에 로컬 주소가 남아 있으면 실패한다', () => {
|
||||
expect(() =>
|
||||
validateEnv(prod({ CORS_ORIGIN: 'http://localhost:5173' })),
|
||||
).toThrow(/CORS_ORIGIN 가 운영에서 쓸 수 없는 주소입니다/);
|
||||
|
||||
expect(() =>
|
||||
validateEnv(prod({ BACKEND_API_URL: 'http://127.0.0.1:3000/api' })),
|
||||
).toThrow(/BACKEND_API_URL 가 운영에서 쓸 수 없는 주소입니다/);
|
||||
});
|
||||
|
||||
it('예시 파일의 example.com 이 그대로면 실패한다', () => {
|
||||
expect(() =>
|
||||
validateEnv(prod({ CORS_ORIGIN: 'https://app.example.com' })),
|
||||
).toThrow(/CORS_ORIGIN 가 운영에서 쓸 수 없는 주소입니다/);
|
||||
});
|
||||
|
||||
it('실제 도메인이면 통과한다', () => {
|
||||
expect(() =>
|
||||
validateEnv(
|
||||
prod({
|
||||
CORS_ORIGIN: 'https://app.myservice.io',
|
||||
BACKEND_API_URL: 'https://api.myservice.io/api',
|
||||
}),
|
||||
),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('ALLOW_LOCALHOST_URL=true 면 공개 주소 검사를 건너뛴다 (운영 이미지 로컬 검증용)', () => {
|
||||
expect(() =>
|
||||
validateEnv(
|
||||
prod({
|
||||
CORS_ORIGIN: 'http://localhost:5173',
|
||||
BACKEND_API_URL: 'http://localhost:3000/api',
|
||||
ALLOW_LOCALHOST_URL: 'true',
|
||||
}),
|
||||
),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('공개 주소 검사는 운영 환경에서만 동작한다', () => {
|
||||
expect(() =>
|
||||
validateEnv({
|
||||
NODE_ENV: 'development',
|
||||
CORS_ORIGIN: 'http://localhost:5173',
|
||||
BACKEND_API_URL: 'http://localhost:3000/api',
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('문제가 여러 개면 한 번에 모두 보여준다', () => {
|
||||
const partial = omit(prod(), 'DB_HOST', 'DB_NAME');
|
||||
|
||||
try {
|
||||
validateEnv({ ...partial, PORT: '0' });
|
||||
fail('예외가 발생해야 한다');
|
||||
} catch (error) {
|
||||
const message = (error as Error).message;
|
||||
expect(message).toContain('DB_HOST');
|
||||
expect(message).toContain('DB_NAME');
|
||||
expect(message).toContain('PORT');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* 환경변수 검증 (부팅 시 fail-fast).
|
||||
*
|
||||
* 설정이 잘못되면 **서버가 뜨지 않게** 한다.
|
||||
* 조용히 기본값으로 굴러가다 운영에서 터지는 것보다, 기동 시점에 실패하는 편이 안전하다.
|
||||
*
|
||||
* `ConfigModule.forRoot({ validate })` 에 연결되어 있다 (app.module.ts).
|
||||
*/
|
||||
|
||||
/** 운영 배포 전에 반드시 교체해야 하는 예시 값들 — `*.example` 에서 복사한 흔적 */
|
||||
const PLACEHOLDER_PATTERNS = [/change[-_]?me/i, /^password$/i, /^secret$/i];
|
||||
|
||||
/** 운영 환경에서 반드시 채워져야 하는 키 */
|
||||
const REQUIRED_IN_PRODUCTION = [
|
||||
'DB_HOST',
|
||||
'DB_USER',
|
||||
'DB_PASSWORD',
|
||||
'DB_NAME',
|
||||
] as const;
|
||||
|
||||
/** 값이 있다면 양의 정수여야 하는 키 */
|
||||
const POSITIVE_INT_KEYS = [
|
||||
'PORT',
|
||||
'DB_PORT',
|
||||
'THROTTLE_TTL_MS',
|
||||
'THROTTLE_LIMIT',
|
||||
] as const;
|
||||
|
||||
/** 운영 환경에서 placeholder 로 남아 있으면 안 되는 키 */
|
||||
const NO_PLACEHOLDER_IN_PRODUCTION = [
|
||||
'DB_PASSWORD',
|
||||
'REDIS_PASSWORD',
|
||||
'JWT_SECRET',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* 운영에서 **공개 주소**여야 하는 키.
|
||||
* 로컬 주소가 남은 채 배포되면 서버는 정상 기동하지만
|
||||
* 브라우저가 API 에 닿지 못하거나 CORS 화이트리스트가 실제 도메인을 막아 **조용히** 실패한다.
|
||||
*/
|
||||
const PUBLIC_URL_IN_PRODUCTION = ['CORS_ORIGIN', 'BACKEND_API_URL'] as const;
|
||||
|
||||
/** 공개 주소로 쓸 수 없는 값 — 로컬 주소와 예시 파일의 예시 도메인 */
|
||||
const NON_PUBLIC_URL_PATTERNS = [
|
||||
/localhost/i,
|
||||
/127\.0\.0\.1/,
|
||||
/\[::1\]/,
|
||||
/0\.0\.0\.0/,
|
||||
/example\.com/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* 위 공개 주소 검사를 건너뛰는 탈출구.
|
||||
* 로컬에서 **운영 이미지를 검증**할 때만 쓴다 (예: graceful shutdown 확인 — .claude/skills/docker/SKILL.md).
|
||||
* 실제 배포에서는 절대 설정하지 않는다.
|
||||
*/
|
||||
const ALLOW_LOCALHOST_URL_KEY = 'ALLOW_LOCALHOST_URL';
|
||||
|
||||
function readString(
|
||||
config: Record<string, unknown>,
|
||||
key: string,
|
||||
): string | undefined {
|
||||
const value = config[key];
|
||||
if (typeof value !== 'string') return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed === '' ? undefined : trimmed;
|
||||
}
|
||||
|
||||
function looksLikePlaceholder(value: string): boolean {
|
||||
return PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(value));
|
||||
}
|
||||
|
||||
function looksNonPublic(value: string): boolean {
|
||||
return NON_PUBLIC_URL_PATTERNS.some((pattern) => pattern.test(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* 환경변수를 검증한다. 문제가 있으면 **모든 문제를 모아** 예외를 던진다.
|
||||
* (하나씩 고쳐가며 재기동하는 낭비를 막기 위해 한 번에 보여준다)
|
||||
*/
|
||||
export function validateEnv(
|
||||
config: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const isProduction = readString(config, 'NODE_ENV') === 'production';
|
||||
const errors: string[] = [];
|
||||
|
||||
// 1. 숫자여야 하는 값 — 비어 있으면 코드의 기본값을 쓰므로 통과시킨다
|
||||
for (const key of POSITIVE_INT_KEYS) {
|
||||
const value = readString(config, key);
|
||||
if (value === undefined) continue;
|
||||
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed <= 0) {
|
||||
errors.push(`${key} 는 양의 정수여야 합니다. (현재 값: "${value}")`);
|
||||
}
|
||||
}
|
||||
|
||||
if (isProduction) {
|
||||
// 2. 운영 필수값 — 없으면 기동 실패
|
||||
for (const key of REQUIRED_IN_PRODUCTION) {
|
||||
if (readString(config, key) === undefined) {
|
||||
errors.push(`${key} 가 설정되지 않았습니다. (운영 환경 필수)`);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 예시 파일의 placeholder 가 그대로 배포되는 것을 막는다
|
||||
for (const key of NO_PLACEHOLDER_IN_PRODUCTION) {
|
||||
const value = readString(config, key);
|
||||
if (value !== undefined && looksLikePlaceholder(value)) {
|
||||
errors.push(
|
||||
`${key} 가 예시 값 그대로입니다. 운영용 값으로 교체해 주세요.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 공개 주소가 로컬 주소·예시 도메인으로 남은 채 배포되는 것을 막는다
|
||||
const allowLocalhostUrl =
|
||||
readString(config, ALLOW_LOCALHOST_URL_KEY) === 'true';
|
||||
|
||||
if (!allowLocalhostUrl) {
|
||||
for (const key of PUBLIC_URL_IN_PRODUCTION) {
|
||||
const value = readString(config, key);
|
||||
if (value !== undefined && looksNonPublic(value)) {
|
||||
errors.push(
|
||||
`${key} 가 운영에서 쓸 수 없는 주소입니다. 실제 도메인으로 교체해 주세요. (현재 값: "${value}")` +
|
||||
` — 로컬에서 운영 이미지를 검증하는 중이라면 ${ALLOW_LOCALHOST_URL_KEY}=true`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new Error(
|
||||
[
|
||||
'환경변수 설정이 올바르지 않아 서버를 시작할 수 없습니다.',
|
||||
...errors.map((message) => ` - ${message}`),
|
||||
'',
|
||||
'루트 .env.{APP_ENV} 를 확인해 주세요. (.claude/rules/env-structure.md)',
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Injectable, Logger, OnApplicationShutdown } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* 종료 로깅 — 컨테이너가 언제·왜 내려갔는지 남긴다.
|
||||
*
|
||||
* `process.on(signal)` 로 직접 잡지 않고 Nest 라이프사이클 훅을 쓰는 이유:
|
||||
* Nest 는 shutdown hook 처리 후 같은 시그널을 재발생시켜 프로세스를 종료하는데,
|
||||
* 직접 등록한 리스너는 이 흐름에 간섭해 종료 코드가 달라진다.
|
||||
*
|
||||
* 이 훅은 `app.close()` 가 끝난 뒤(= 처리 중인 요청과 커넥션 정리 후) 호출되므로,
|
||||
* 로그가 남았다는 것은 정상 종료가 완료되었다는 뜻이다.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ShutdownLogger implements OnApplicationShutdown {
|
||||
private readonly logger = new Logger(ShutdownLogger.name);
|
||||
|
||||
onApplicationShutdown(signal?: string): void {
|
||||
this.logger.log(
|
||||
`애플리케이션을 정상 종료했습니다. (사유: ${signal ?? '애플리케이션 종료 요청'})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { utilities as nestWinstonUtilities } from 'nest-winston';
|
||||
import * as winston from 'winston';
|
||||
|
||||
// 표준 로거 설정 — console.log 대체용
|
||||
// 운영 환경에서는 파일 로테이션 또는 외부 로그 수집기(예: Loki, ELK) 추가 권장
|
||||
export const winstonConfig: winston.LoggerOptions = {
|
||||
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
|
||||
transports: [
|
||||
new winston.transports.Console({
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.ms(),
|
||||
nestWinstonUtilities.format.nestLike('App', {
|
||||
colors: process.env.NODE_ENV !== 'production',
|
||||
prettyPrint: true,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { parsePositiveInt } from './env';
|
||||
|
||||
describe('parsePositiveInt', () => {
|
||||
it('정상적인 양의 정수 문자열을 숫자로 변환한다', () => {
|
||||
expect(parsePositiveInt('60000', 100)).toBe(60000);
|
||||
});
|
||||
|
||||
it('값이 없으면 기본값을 반환한다', () => {
|
||||
expect(parsePositiveInt(undefined, 100)).toBe(100);
|
||||
});
|
||||
|
||||
it('빈 문자열이면 기본값을 반환한다 (docker-compose 미정의 변수 대응)', () => {
|
||||
// compose 는 정의되지 않은 변수를 빈 문자열로 주입한다 — Number('') === 0 이므로 방어가 필요하다
|
||||
expect(parsePositiveInt('', 100)).toBe(100);
|
||||
expect(parsePositiveInt(' ', 100)).toBe(100);
|
||||
});
|
||||
|
||||
it('숫자가 아니면 기본값을 반환한다', () => {
|
||||
expect(parsePositiveInt('abc', 100)).toBe(100);
|
||||
});
|
||||
|
||||
it('0 이하이거나 소수면 기본값을 반환한다', () => {
|
||||
expect(parsePositiveInt('0', 100)).toBe(100);
|
||||
expect(parsePositiveInt('-5', 100)).toBe(100);
|
||||
expect(parsePositiveInt('1.5', 100)).toBe(100);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* 환경변수 파싱 유틸 (순수 함수).
|
||||
*
|
||||
* docker-compose 는 정의되지 않은 변수를 **빈 문자열**로 주입한다.
|
||||
* `Number('')` 는 0 이므로 `??` 만으로는 기본값이 적용되지 않는다 — 이 함수로 방어한다.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 환경변수를 양의 정수로 파싱한다.
|
||||
* 값이 없거나(undefined·빈 문자열) 숫자가 아니거나 0 이하면 기본값을 반환한다.
|
||||
*/
|
||||
export function parsePositiveInt(
|
||||
value: string | undefined,
|
||||
fallback: number,
|
||||
): number {
|
||||
if (value === undefined || value.trim() === '') return fallback;
|
||||
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed <= 0) return fallback;
|
||||
|
||||
return parsed;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// 공통 포맷터 — 부수효과 없는 순수 함수만 작성
|
||||
|
||||
/**
|
||||
* Date 또는 ISO 문자열을 'YYYY-MM-DD' 형식으로 변환
|
||||
*/
|
||||
export function formatDate(input: Date | string): string {
|
||||
const date = typeof input === 'string' ? new Date(input) : input;
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const yyyy = date.getFullYear();
|
||||
const mm = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const dd = String(date.getDate()).padStart(2, '0');
|
||||
return `${yyyy}-${mm}-${dd}`;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { INestApplication, ValidationPipe } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import type { Response } from 'supertest';
|
||||
import { App } from 'supertest/types';
|
||||
|
||||
import { AppModule } from '@/app.module';
|
||||
import { HttpExceptionFilter } from '@/common/filters/http-exception.filter';
|
||||
import { TransformInterceptor } from '@/common/interceptors/transform.interceptor';
|
||||
import { RequestIdMiddleware } from '@/common/middleware/request-id.middleware';
|
||||
|
||||
/**
|
||||
* 세 플랫폼이 공유하는 응답 계약을 실제 HTTP 요청으로 검증한다.
|
||||
*
|
||||
* ⚠️ DB 연결이 필요하다 (AppModule 이 TypeORM 을 초기화한다).
|
||||
* 로컬: docker 개발 스택을 띄운 뒤 실행. CI: postgres 서비스 컨테이너 사용.
|
||||
*/
|
||||
/** supertest 의 body 는 any 이므로 계약 형태로 좁혀서 읽는다 */
|
||||
interface ContractBody {
|
||||
success?: boolean;
|
||||
data?: {
|
||||
items?: unknown[];
|
||||
pageInfo?: {
|
||||
hasNext: boolean;
|
||||
nextCursor: string | null;
|
||||
total: number | null;
|
||||
};
|
||||
};
|
||||
error?: { code?: string; message?: string; traceId?: string };
|
||||
status?: string;
|
||||
details?: unknown;
|
||||
}
|
||||
|
||||
const body = (res: Response): ContractBody => res.body as ContractBody;
|
||||
|
||||
describe('응답 계약 (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||
imports: [AppModule],
|
||||
}).compile();
|
||||
|
||||
app = moduleFixture.createNestApplication();
|
||||
|
||||
// main.ts 와 동일한 전역 설정을 적용해야 실제 응답과 같아진다
|
||||
app.setGlobalPrefix('api');
|
||||
app.use(new RequestIdMiddleware().use.bind(new RequestIdMiddleware()));
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
app.useGlobalInterceptors(new TransformInterceptor(app.get(Reflector)));
|
||||
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('성공 응답은 { success, data } 로 감싸진다', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/users')
|
||||
.expect(200);
|
||||
|
||||
expect(body(res).success).toBe(true);
|
||||
expect(body(res).data).toHaveProperty('items');
|
||||
expect(body(res).data).toHaveProperty('pageInfo');
|
||||
});
|
||||
|
||||
it('목록 응답의 pageInfo 는 공유 계약 형태를 지킨다', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/users')
|
||||
.expect(200);
|
||||
|
||||
const pageInfo = body(res).data?.pageInfo;
|
||||
|
||||
expect(Object.keys(pageInfo ?? {}).sort()).toEqual([
|
||||
'hasNext',
|
||||
'nextCursor',
|
||||
'total',
|
||||
]);
|
||||
expect(typeof pageInfo?.hasNext).toBe('boolean');
|
||||
expect(pageInfo?.nextCursor).toBeNull();
|
||||
expect(typeof pageInfo?.total).toBe('number');
|
||||
});
|
||||
|
||||
it('없는 리소스는 RES_001 과 traceId 를 반환한다', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/users/999999')
|
||||
.expect(404);
|
||||
|
||||
expect(body(res).success).toBe(false);
|
||||
expect(body(res).error?.code).toBe('RES_001');
|
||||
expect(typeof body(res).error?.traceId).toBe('string');
|
||||
});
|
||||
|
||||
it('검증 실패는 VAL_001 이며 상세 사유를 노출하지 않는다', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/api/users')
|
||||
.send({ email: '잘못된형식', password: '1' })
|
||||
.expect(400);
|
||||
|
||||
expect(body(res).error?.code).toBe('VAL_001');
|
||||
// class-validator 의 개별 메시지가 그대로 새어나가면 안 된다
|
||||
expect(JSON.stringify(body(res))).not.toContain('must be an email');
|
||||
});
|
||||
|
||||
it('DTO 에 없는 필드는 거부된다 (forbidNonWhitelisted)', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/users?정의되지않은파라미터=1')
|
||||
.expect(400);
|
||||
|
||||
expect(body(res).error?.code).toBe('VAL_001');
|
||||
});
|
||||
|
||||
it('헬스체크는 표준 래퍼 없이 terminus 원본 형식을 반환한다', async () => {
|
||||
const res = await request(app.getHttpServer()).get('/api/health');
|
||||
|
||||
expect(body(res)).not.toHaveProperty('success');
|
||||
expect(body(res)).toHaveProperty('status');
|
||||
expect(body(res)).toHaveProperty('details');
|
||||
});
|
||||
|
||||
it('모든 응답에 x-request-id 헤더가 붙는다', async () => {
|
||||
const res = await request(app.getHttpServer()).get('/api/users');
|
||||
|
||||
expect(typeof res.headers['x-request-id']).toBe('string');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"moduleFileExtensions": [
|
||||
"js",
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "..",
|
||||
"testEnvironment": "node",
|
||||
"moduleNameMapper": {
|
||||
"^@/(.*)$": "<rootDir>/src/$1"
|
||||
},
|
||||
"testRegex": "test/.*\\.e2e-spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"resolvePackageJsonExports": true,
|
||||
"esModuleInterop": true,
|
||||
"isolatedModules": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2023",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
},
|
||||
"incremental": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"strictNullChecks": true,
|
||||
"noImplicitAny": true,
|
||||
"strictBindCallApply": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"watchOptions": {
|
||||
"watchFile": "priorityPollingInterval",
|
||||
"watchDirectory": "dynamicPriorityPolling",
|
||||
"fallbackPolling": "dynamicPriority"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user