diff --git a/.claude/rules/api-design.md b/.claude/rules/api-design.md new file mode 100644 index 0000000..32df3d5 --- /dev/null +++ b/.claude/rules/api-design.md @@ -0,0 +1,64 @@ +# API 설계 규약 + +세 클라이언트가 공유하는 계약이므로, 아래 규약은 백엔드 단독으로 바꾸지 않는다. + +## 경로 · 메서드 + +- 모든 라우트는 글로벌 prefix `/api` 아래에 놓인다 (`main.ts`). 클라이언트 baseURL 도 `/api` 를 포함한다. +- 리소스는 **복수형 명사**, 소문자 kebab-case: `/users`, `/order-items` +- 동사를 경로에 넣지 않는다. 상태 변경이 필요하면 하위 리소스로 표현한다. + - ❌ `POST /users/1/doDeactivate` + - ✅ `POST /users/1/deactivation` + +| 메서드 | 용도 | 성공 상태 | +| --- | --- | --- | +| GET | 조회 (부수효과 없음) | 200 | +| POST | 생성 · 비멱등 작업 | 201 (생성) / 200 | +| PATCH | 부분 수정 | 200 | +| PUT | 전체 교체 | 200 | +| DELETE | 삭제 | 204 (`@SkipTransform()`) 또는 200 | + +## 쿼리 파라미터 + +| 용도 | 파라미터 | 비고 | +| --- | --- | --- | +| 커서 페이지네이션 | `cursor`, `limit` | 기본 20 / 최대 100 ([[response-format]]) | +| 오프셋 페이지네이션 | `page`, `limit` | 전체 페이지 수가 UI 에 필요할 때만 | +| 정렬 | `sort=createdAt:desc` | `필드:방향`, 콤마로 다중 지정 | +| 검색 | `q` | 자유 텍스트 검색 | +| 필터 | 필드명 그대로 (`status=active`) | 화이트리스트 DTO 로만 수용 | + +- 모든 쿼리는 DTO(`class-validator`)로 검증한다. `forbidNonWhitelisted` 때문에 미정의 파라미터는 400(VAL_001)이 된다. + +## 데이터 표현 + +- **날짜/시각**: ISO 8601 UTC 문자열 (`2026-09-16T13:22:16.000Z`). 타임존 변환은 클라이언트 책임. +- **ID**: 노출용 식별자는 문자열로 직렬화해도 되지만 타입을 도메인 내에서 일관되게 유지한다. +- **금액**: 소수 오차를 피해 최소 단위 정수(원 단위)로 주고받는다. +- **불리언 필드**: `is`/`has` 접두어 (`isActive`, `hasNext`). +- **필드명**: JSON 은 camelCase. DB 컬럼명이 snake_case 여도 응답에서 변환한다. +- `null` 과 필드 생략을 혼용하지 않는다 — "값 없음"은 `null` 로 통일한다. + +## 버전 관리 + +- 호환성을 깨는 변경(필드 삭제, 타입 변경, 의미 변경)이 필요하면 경로 버전을 올린다: `/api/v2/users` +- 필드 **추가**는 호환 변경이므로 버전을 올리지 않는다. 클라이언트는 모르는 필드를 무시해야 한다. +- 제거 예정 필드는 먼저 문서에 `deprecated` 로 표시하고, 클라이언트 전환 후 삭제한다. + +## 문서화 (Swagger) + +- 모든 컨트롤러에 `@ApiTags()`, 모든 엔드포인트에 `@ApiOperation()`. +- 성공 응답은 `@ApiStandardResponse()`, 실패 응답은 `@ApiErrorResponse('CODE')` 로 문서화한다 + — 래퍼 구조와 에러 레지스트리가 자동 반영되어 문서와 구현이 어긋나지 않는다 ([[response-format]]). +- 모든 DTO 필드에 `@ApiProperty()` + 한국어 `description`. + +## 신규 엔드포인트 체크 + +- [ ] 경로가 복수형 리소스 + 동사 없음 +- [ ] 입력은 DTO 검증, 출력은 응답 DTO 정의 +- [ ] 목록이면 페이지네이션 적용 +- [ ] 실패 경로마다 에러 코드 지정 ([[error-codes]]) +- [ ] Swagger 데코레이터 작성 +- [ ] 세 클라이언트 중 사용하는 쪽의 타입/모델 갱신 + +> 응답 구조는 [[response-format]], 에러는 [[error-codes]], 구현 규칙은 [[nestjs]] 참조. diff --git a/.claude/rules/response-format.md b/.claude/rules/response-format.md index e3014f3..9efd36d 100644 --- a/.claude/rules/response-format.md +++ b/.claude/rules/response-format.md @@ -1,21 +1,90 @@ ---- -name: response-format -description: 모든 API 응답이 따르는 표준 응답 래퍼(success/data/error) 규칙. SSOT는 backend TransformInterceptor + HttpExceptionFilter. ---- - # 표준 응답 포맷 (Global Response Wrapper) 모든 API 응답은 아래 구조로 통일한다. -(SSOT: backend `TransformInterceptor` + `HttpExceptionFilter` — [[nestjs]] 참조) +SSOT: backend `TransformInterceptor` + `HttpExceptionFilter` ([[nestjs]] 참조) ```jsonc // 성공 { "success": true, "data": { /* ... */ } } // 실패 -{ "success": false, "error": { "code": "VAL_001", "message": "..." } } +{ "success": false, "error": { "code": "VAL_001", "message": "...", "traceId": "3f1c0a2e-..." } } ``` -- 프론트/플러터 인터셉터는 `success: true` 면 `data` 만 언래핑하여 반환한다. -- `success: false` 이거나 HTTP 4xx/5xx 면 `error.code` 로 메시지를 매핑한다. -- 에러 코드 ↔ 메시지 매핑은 [[error-codes]] 참조. +- 컨트롤러는 **raw 데이터만 반환**한다. `{success,data}` 래핑은 인터셉터가 담당 — 직접 래핑 금지. +- 클라이언트 인터셉터는 `success: true` 면 `data` 만 언래핑해 반환한다. +- 실패는 **항상 `error.code` 로 분기**한다. `message` 로 분기하지 않는다 ([[error-codes]]). +- `traceId` 는 서버가 요청마다 발급하는 추적 ID(`x-request-id`)다. 응답 헤더로도 함께 내려간다. + +## 비즈니스 실패도 4xx 로 내린다 + +- 백엔드는 `success: false` 를 **항상 4xx/5xx 와 함께** 내려보낸다. HTTP 200 + `success:false` 조합은 만들지 않는다. +- 단, 클라이언트 인터셉터는 외부 게이트웨이 등이 200 으로 감싸는 경우를 대비해 **방어적으로 이 분기를 유지**한다. + +## 래핑 예외 (`@SkipTransform()`) + +본문 구조를 바꾸면 안 되는 응답은 백엔드에서 `@SkipTransform()` 을 붙여 래핑을 건너뛴다. + +```typescript +@Get('export') +@SkipTransform() // 파일 스트림 — { success, data } 로 감싸면 깨진다 +exportCsv(@Res() res: Response) { /* ... */ } +``` + +적용 대상: 파일 다운로드·스트림, 리다이렉트, `204 No Content`, 외부 규격을 따라야 하는 웹훅 응답, +그리고 **기계가 소비하는 엔드포인트**(헬스체크 등). + +### 헬스체크는 표준 포맷에서 제외한다 + +`/api/health` 는 사람이 아니라 모니터링 도구가 읽는다. 래퍼로 감싸거나 실패를 `SYS_001` 로 덮어쓰면 +**어느 구성요소가 죽었는지가 사라진다.** 그래서 성공·실패 모두 terminus 원본 형식을 그대로 내보낸다. + +```jsonc +// 200 — 정상 +{ "status": "ok", "info": { "database": { "status": "up" } }, "error": {}, "details": { ... } } + +// 503 — 실패 (원인이 보인다) +{ "status": "error", "info": {}, "error": { "database": { "status": "down", "message": "..." } }, ... } +``` + +구현: `HealthController` 에 `@SkipTransform()` 을 붙이고, terminus 의 `ServiceUnavailableException` 은 +컨트롤러에서 직접 잡아 503 + 원본 본문을 반환한다(전역 필터까지 가지 않게 한다). +같은 성격의 엔드포인트를 추가할 때 이 패턴을 재사용한다. + +## 목록 응답 (페이지네이션) + +목록 API 의 `data` 는 **항상 아래 구조**를 가진다. 배열을 그대로 반환하지 않는다. + +```jsonc +{ + "success": true, + "data": { + "items": [ /* ... */ ], + "pageInfo": { + "hasNext": true, + "nextCursor": "eyJpZCI6MTQzfQ==", // 마지막 페이지면 null + "total": 143 // 계산 비용이 크면 null 허용 + } + } +} +``` + +- 구현 SSOT: backend `common/dto/pagination.dto.ts` + (`CursorPaginationQueryDto` · `OffsetPaginationQueryDto` · `PageInfoDto` · `toPaginatedResult()`) +- 클라이언트 타입: frontend `src/shared/types/pagination.ts`, flutter `UserRepository.getUsers()` 패턴 +- **커서 기반이 기본**이다. 전체 페이지 수가 UI 에 필요한 경우에만 오프셋을 쓴다. +- `limit` 기본값 20, 최대 100 — 무제한 조회를 허용하지 않는다. + +## Swagger 문서 일치 + +컨트롤러는 raw 를 반환하지만 실제 응답은 래핑되므로, `@ApiResponse({ type: Dto })` 를 그대로 쓰면 문서와 실응답이 어긋난다. + +```typescript +@ApiStandardResponse(UserResponseDto, { description: '사용자 조회 성공' }) +@ApiErrorResponse('RES_001', '사용자를 찾을 수 없음') +``` + +- `ApiStandardResponse` / `ApiErrorResponse` 는 `common/decorators/api-standard-response.decorator.ts` 제공. +- `ApiErrorResponse` 는 상태 코드·메시지를 에러 레지스트리에서 가져오므로 문서가 구현과 자동으로 일치한다. + +> 에러 코드 ↔ 메시지 매핑은 [[error-codes]], API 설계 규약은 [[api-design]] 참조. diff --git a/.gitignore b/.gitignore index 976e0ab..c4d3512 100644 --- a/.gitignore +++ b/.gitignore @@ -9,10 +9,12 @@ # ========================================== # 도커 영속 데이터 # ========================================== -data/ -!data/.gitkeep -db-data/ -redis-data/ +# ⚠️ 루트 기준으로 고정한다(앞의 /). 'data/' 로 두면 모든 depth 의 data 디렉터리가 무시되어 +# flutter/lib/features/<도메인>/data/ 같은 소스 코드까지 커밋되지 않는다. +/data/ +!/data/.gitkeep +/db-data/ +/redis-data/ # ========================================== # 의존성/빌드 산출물 diff --git a/backend/src/common/decorators/api-standard-response.decorator.ts b/backend/src/common/decorators/api-standard-response.decorator.ts new file mode 100644 index 0000000..994ef86 --- /dev/null +++ b/backend/src/common/decorators/api-standard-response.decorator.ts @@ -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>( + 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', + }, + }, + }, + }, + }, + }); +} diff --git a/backend/src/common/decorators/skip-transform.decorator.ts b/backend/src/common/decorators/skip-transform.decorator.ts new file mode 100644 index 0000000..7afaaeb --- /dev/null +++ b/backend/src/common/decorators/skip-transform.decorator.ts @@ -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); diff --git a/backend/src/common/dto/pagination.dto.ts b/backend/src/common/dto/pagination.dto.ts new file mode 100644 index 0000000..eb275fb --- /dev/null +++ b/backend/src/common/dto/pagination.dto.ts @@ -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 { + items: T[]; + pageInfo: PageInfoDto; +} + +/** 조회 결과를 표준 목록 응답으로 변환한다. */ +export function toPaginatedResult( + items: T[], + pageInfo: Partial = {}, +): PaginatedResult { + return { + items, + pageInfo: { + hasNext: pageInfo.hasNext ?? false, + nextCursor: pageInfo.nextCursor ?? null, + total: pageInfo.total ?? null, + }, + }; +} diff --git a/backend/src/common/interceptors/transform.interceptor.ts b/backend/src/common/interceptors/transform.interceptor.ts index e1b3353..5f9095d 100644 --- a/backend/src/common/interceptors/transform.interceptor.ts +++ b/backend/src/common/interceptors/transform.interceptor.ts @@ -1,31 +1,47 @@ import { + CallHandler, + ExecutionContext, Injectable, NestInterceptor, - ExecutionContext, - CallHandler, } 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 { - success: boolean; + success: true; // 핸들러가 undefined/null 을 반환하면 null 로 정규화되므로 nullable data: T | null; } +/** + * 성공 응답을 { success: true, data } 로 래핑한다. + * `@SkipTransform()` 이 붙은 핸들러는 원본 응답을 그대로 통과시킨다. + */ @Injectable() export class TransformInterceptor implements NestInterceptor< T, - StandardResponse + StandardResponse | T > { + constructor(private readonly reflector: Reflector) {} + intercept( - _context: ExecutionContext, + context: ExecutionContext, next: CallHandler, - ): Observable> { - // 이미 Http 응답객체인 경우 등 예외처리가 필요할 수 있으나 기본적으로 data 래핑 - return (next.handle() as Observable).pipe( + ): Observable | T> { + const skip = this.reflector.getAllAndOverride(SKIP_TRANSFORM_KEY, [ + context.getHandler(), + context.getClass(), + ]); + + const source = next.handle() as Observable; + if (skip) return source; + + return source.pipe( map((data) => ({ - success: true, + success: true as const, data: data ?? null, })), ); diff --git a/backend/src/common/middleware/request-id.middleware.ts b/backend/src/common/middleware/request-id.middleware.ts new file mode 100644 index 0000000..79deba4 --- /dev/null +++ b/backend/src/common/middleware/request-id.middleware.ts @@ -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(); + } +} diff --git a/backend/src/modules/user/dto/user-response.dto.ts b/backend/src/modules/user/dto/user-response.dto.ts new file mode 100644 index 0000000..2a63326 --- /dev/null +++ b/backend/src/modules/user/dto/user-response.dto.ts @@ -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; +} diff --git a/backend/src/modules/user/user.controller.ts b/backend/src/modules/user/user.controller.ts index 2c31ad2..619083b 100644 --- a/backend/src/modules/user/user.controller.ts +++ b/backend/src/modules/user/user.controller.ts @@ -5,15 +5,18 @@ import { Param, ParseIntPipe, Post, + Query, } from '@nestjs/common'; +import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; + import { - ApiBearerAuth, - ApiOperation, - ApiResponse, - ApiTags, -} from '@nestjs/swagger'; + 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') @@ -22,18 +25,34 @@ import { CreateUserDto } from './dto/create-user.dto'; 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: '사용자 단건 조회' }) - @ApiResponse({ status: 200, description: '사용자 조회 성공' }) - @ApiResponse({ status: 404, description: '사용자를 찾을 수 없음 (RES_001)' }) + @ApiStandardResponse(UserResponseDto, { description: '사용자 조회 성공' }) + @ApiErrorResponse('RES_001', '사용자를 찾을 수 없음') findOne(@Param('id', ParseIntPipe) id: number) { return this.userService.findOne(id); } @Post() @ApiOperation({ summary: '사용자 생성' }) - @ApiResponse({ status: 201, description: '사용자 생성 성공' }) - @ApiResponse({ status: 400, description: '입력값 검증 실패 (VAL_001)' }) + @ApiStandardResponse(UserResponseDto, { + status: 201, + description: '사용자 생성 성공', + }) + @ApiErrorResponse('VAL_001', '입력값 검증 실패') + @ApiErrorResponse('BIZ_001', '이메일 중복 등 비즈니스 규칙 위반') create(@Body() dto: CreateUserDto) { return this.userService.create(dto); } diff --git a/backend/src/modules/user/user.service.ts b/backend/src/modules/user/user.service.ts index 6fbdad2..07ec494 100644 --- a/backend/src/modules/user/user.service.ts +++ b/backend/src/modules/user/user.service.ts @@ -1,27 +1,57 @@ -import { Injectable, NotFoundException } from '@nestjs/common'; +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 { - // 임시 인메모리 저장소 — Repository 도입 시 교체 - private readonly users = new Map< - number, - { id: number; email: string; name: string } - >(); + // 임시 인메모리 저장소 — TypeORM Repository 도입 시 교체 + private readonly users = new Map(); - findOne(id: number) { + findOne(id: number): UserResponseDto { const user = this.users.get(id); if (!user) { - // 404 → 전역 필터에서 RES_001 로 변환됨 - throw new NotFoundException(); + // 사용자 노출 실패는 항상 에러 코드와 함께 던진다. + throw new BusinessException('RES_001', { context: { userId: id } }); } return user; } - create(dto: CreateUserDto) { + /** 커서 기반 목록 조회 샘플 — 목록 API 는 항상 페이지네이션을 적용한다. */ + findMany(limit: number, cursor?: string): PaginatedResult { + 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 = { id, email: dto.email, name: dto.name }; + const user: UserResponseDto = { id, email: dto.email, name: dto.name }; this.users.set(id, user); return user; } diff --git a/flutter/lib/features/user/data/models/user_model.dart b/flutter/lib/features/user/data/models/user_model.dart new file mode 100644 index 0000000..3624e94 --- /dev/null +++ b/flutter/lib/features/user/data/models/user_model.dart @@ -0,0 +1,27 @@ +/// 사용자 모델 — 백엔드 UserResponseDto 와 1:1 대응한다. +/// (freezed/json_serializable 도입 시 이 클래스를 생성 모델로 교체) +class UserModel { + const UserModel({ + required this.id, + required this.email, + required this.name, + }); + + final int id; + final String email; + final String name; + + factory UserModel.fromJson(Map json) { + return UserModel( + id: json['id'] as int, + email: json['email'] as String, + name: json['name'] as String, + ); + } + + Map toJson() => { + 'id': id, + 'email': email, + 'name': name, + }; +} diff --git a/flutter/lib/features/user/data/repositories/user_repository.dart b/flutter/lib/features/user/data/repositories/user_repository.dart new file mode 100644 index 0000000..0ae4164 --- /dev/null +++ b/flutter/lib/features/user/data/repositories/user_repository.dart @@ -0,0 +1,44 @@ +import 'package:dio/dio.dart'; + +import '../models/user_model.dart'; + +/// 사용자 API 호출 구현체 — 새 도메인은 이 패턴을 복제한다. +/// +/// 응답 언래핑({ success, data } → data)과 에러 코드 매핑은 dio 인터셉터가 담당하므로 +/// 리포지토리는 파싱만 책임진다. (여기서 try/catch 로 메시지를 만들지 않는다) +class UserRepository { + const UserRepository(this._dio); + + final Dio _dio; + + Future getUser(int id) async { + final response = await _dio.get>('/users/$id'); + return UserModel.fromJson(response.data!); + } + + /// 커서 기반 목록 조회 — 목록 API 는 항상 페이지네이션을 적용한다. + Future<({List items, String? nextCursor, bool hasNext})> getUsers({ + int limit = 20, + String? cursor, + }) async { + final response = await _dio.get>( + '/users', + queryParameters: { + 'limit': limit, + 'cursor': ?cursor, + }, + ); + + final data = response.data!; + final items = (data['items'] as List) + .map((json) => UserModel.fromJson(json as Map)) + .toList(); + final pageInfo = data['pageInfo'] as Map; + + return ( + items: items, + nextCursor: pageInfo['nextCursor'] as String?, + hasNext: pageInfo['hasNext'] as bool? ?? false, + ); + } +} diff --git a/frontend/src/shared/types/pagination.ts b/frontend/src/shared/types/pagination.ts new file mode 100644 index 0000000..cea9670 --- /dev/null +++ b/frontend/src/shared/types/pagination.ts @@ -0,0 +1,25 @@ +// 목록 응답 공유 계약 — 백엔드 PaginatedResult 와 동일 구조 +// (백엔드: backend/src/common/dto/pagination.dto.ts) + +export interface PageInfo { + /** 다음 페이지 존재 여부 */ + hasNext: boolean + /** 다음 요청에 넘길 커서. 마지막 페이지면 null */ + nextCursor: string | null + /** 전체 개수. 계산 비용이 큰 경우 null 일 수 있다. */ + total: number | null +} + +export interface PaginatedResult { + items: T[] + pageInfo: PageInfo +} + +/** 커서 기반 목록 조회 쿼리 파라미터 */ +export interface CursorPaginationQuery { + cursor?: string + limit?: number +} + +/** 목록 API 기본 조회 개수 — 백엔드 PAGINATION_DEFAULT_LIMIT 와 동일 */ +export const DEFAULT_PAGE_SIZE = 20