[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,94 +1,202 @@
---
id: wiki-2026-0508-백엔드-프론트엔드-데이터-변환-data-transforma
title: 백엔드 프론트엔드 데이터 변환(Data Transformation between Backend and Frontend)
title: 백엔드-프론트엔드 데이터 변환(Data Transformation between Backend and Frontend)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-6AC944]
aliases: [DTO, Data Transformation, API 응답 변환, snake_case to camelCase]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [frontend, backend, api, data-modeling, typescript]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - 백엔드-프론트엔드 데이터 변환(Data Transformation between [[Backend|Backend]] and [[Frontend|Frontend]])"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: react
---
# [[백엔드-프론트엔드 데이터 변환(Data Transformation between Backend and Frontend)|백엔드-프론트엔드 데이터 변환(Data Transformation between Backend and Frontend]]
# 백엔드-프론트엔드 데이터 변환(Data Transformation between Backend and Frontend)
## 📌 한 줄 통찰 (The Karpathy Summary)
> 백엔드-프론트엔드 데이터 변환은 외부 서버(백엔드)에서 수신한 데이터를 프론트엔드 애플리케이션의 모델 구조에 맞게 매핑하고 파싱하는 과정입니다 [1-3]. 이 과정에서 타입스크립트의 `satisfies` 키워드나 파싱(Parsing) 패턴을 활용하면 오타, 초과 속성 할당 등의 구조적 불일치를 사전에 방지하고 견고한 타입 안전성을 확보할 수 있습니다 [3-5].
## 한 줄
> **"매 server payload 매 client model 의 일치 안함 — adapter 의 boundary"**. 매 DB schema (snake_case, nullable, denormalized) 매 UI model (camelCase, optional, normalized)의 mismatch 의 explicit 의 mapping. 매 2026 의 Zod + tRPC + GraphQL codegen 의 type-safe automation.
## 📖 구조화된 지식 (Synthesized Content)
- **데이터 매핑 과정의 취약성:** 외부 백엔드 시스템에서 응답으로 도착하는 데이터는 프론트엔드가 요구하는 형식과 다를 수 있습니다 [3]. 이 외부 데이터를 프론트엔드 타입에 맞춰 매핑할 때, 개발자가 속성 이름을 잘못 입력하거나 원치 않는 잉여 필드를 포함하는 등의 오류를 도입하기 쉽습니다 [3].
- **`satisfies` 키워드를 활용한 엄격한 타입 강제:** 백엔드 데이터를 프론트엔드 모델로 변환하는 매핑 함수 내부에서 `satisfies` 키워드를 사용하면, 오직 대상 타입에 정의된 유효한 속성만 포함되도록 엄격하게 강제할 수 있습니다 [5]. 이를 통해 초과 속성이나 오타 등의 오류가 매핑 과정에서 발생하는 것을 컴파일 타임에 효과적으로 포착할 수 있습니다 [2, 5].
- **타입 캐스팅(`as`)의 한계:** 데이터 변환 시 단순한 타입 캐스팅(`as`)을 사용하는 것은 지양해야 합니다. 타입 캐스팅은 잉여 속성 검사([[Excess Property Checking|Excess Property Checking]])를 강제하지 않으므로 추가적인 속성이 존재하더라도 에러를 발생시키지 않아, 예측하지 못한 조용한 오류(silent error)를 유발할 수 있습니다 [5].
- **'검증하지 말고 파싱하라(Parse, don't validate)' 원칙:** 서버의 응답을 받는 것과 같은 시스템의 경계(Boundary) 지점에서, 타입이 없거나 덜 엄격한 데이터를 잘 정의된 타입의 데이터로 초기 단계에서부터 파싱해야 합니다 [1, 4]. 단순히 데이터 유효성만 체크하는 데 그치지 않고, Zod와 같은 라이브러리를 통해 신뢰할 수 있는 구체적인 객체로 파싱한 후 시스템 내부에 전달해야 견고함을 유지할 수 있습니다 [1, 6].
- **원격 소스 타입에 대한 의존성 주의:** 백엔드와 같은 원격 소스에서 가져오는 데이터의 형태를 기반으로 타입스크립트의 타입이나 인터페이스를 정의하고, 이를 유일한 '진실의 원천(Source of Truth)'으로 삼는 것은 피해야 합니다 [7]. 원격 소스의 형태는 프론트엔드의 정의와 언제든지 동기화가 어긋날 위험이 있기 때문입니다 [7].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 mismatch dimensions
- **Naming**: `user_name` (snake) ↔ `userName` (camel).
- **Types**: `1693497600` (Unix epoch) ↔ `Date` object, `"2026-05-10"``Date`.
- **Shape**: nested vs flat, `{user: {profile: {...}}}``{userId, userName, ...}`.
- **Nullability**: `null` (DB) ↔ `undefined` (TS optional).
- **Enums**: `0/1/2``'pending' | 'active' | 'closed'`.
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[satisfies Keyword|satisfies Keyword]], Parse, don't validate, Excess Property Checking, [[Structural Typing|Structural Typing]]
- **Projects/Contexts:** [[Inventory Management Example|Inventory Management Example]] (외부 백엔드 응답을 프론트엔드의 `InventoryItem` 타입으로 매핑할 때 오류를 방지하는 실제 사용 시나리오 [2, 3])
- **Contradictions/Notes:** 소스 데이터에 따르면 데이터 변환 과정에서 강제 타입 단언([[Type Casting|Type Casting]], `as`)을 사용하여 타입을 덮어씌우는 것은 잉여 속성을 걸러내지 못하므로 안전하지 않으며, 이를 보완하기 위해 런타임 오류 가능성을 원천 차단하는 `satisfies` 연산자의 사용이 권장됩니다 [5, 8].
### 매 layers (Clean Architecture)
- **DTO** (Data Transfer Object) — wire format, snake_case, raw.
- **Domain Model** — business rules, computed props.
- **View Model** — UI-specific (formatted strings, derived flags).
---
*Last updated: 2026-04-18*
### 매 응용
1. REST API 의 camelCase 변환.
2. GraphQL → TypeScript codegen.
3. Date/Decimal 의 typed objects 변환.
4. Form 의 server payload 의 transform.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 1. snake_case ↔ camelCase (humps library)
```typescript
import { camelizeKeys, decamelizeKeys } from 'humps';
**언제 이 지식을 쓰는가:**
- *(TODO)*
const apiResponse = { user_name: 'Alice', created_at: '2026-05-10' };
const camel = camelizeKeys(apiResponse) as { userName: string; createdAt: string };
// → { userName: 'Alice', createdAt: '2026-05-10' }
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
const payload = decamelizeKeys({ userName: 'Bob' });
// → { user_name: 'Bob' }
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Zod schema (validate + transform)
```typescript
import { z } from 'zod';
**선택 A를 써야 할 때:**
- *(TODO)*
const UserDTO = z.object({
user_id: z.number(),
user_name: z.string(),
created_at: z.string(),
is_active: z.union([z.literal(0), z.literal(1)]),
}).transform(d => ({
userId: d.user_id,
userName: d.user_name,
createdAt: new Date(d.created_at),
isActive: d.is_active === 1,
}));
**선택 B를 써야 할 때:**
- *(TODO)*
type User = z.infer<typeof UserDTO>;
// { userId: number; userName: string; createdAt: Date; isActive: boolean }
**기본값:**
> *(TODO)*
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
const json = await res.json();
return UserDTO.parse(json); // validates + transforms
}
```
## ❌ 안티패턴 (Anti-Patterns)
### 3. TanStack Query select (boundary transform)
```typescript
import { useQuery } from '@tanstack/react-query';
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
export function useUser(id: number) {
return useQuery({
queryKey: ['user', id],
queryFn: async () => {
const res = await fetch(`/api/users/${id}`);
return res.json();
},
select: (data) => UserDTO.parse(data), // transform per render
});
}
```
### 4. Date / Decimal serialization
```typescript
// server JSON cannot carry Date/BigInt natively
import Decimal from 'decimal.js';
const PaymentDTO = z.object({
amount: z.string().transform(s => new Decimal(s)),
paid_at: z.string().datetime().transform(s => new Date(s)),
});
// reverse: outgoing
function toPayload(p: { amount: Decimal; paidAt: Date }) {
return {
amount: p.amount.toString(),
paid_at: p.paidAt.toISOString(),
};
}
```
### 5. tRPC (no transform needed — type-safe RPC)
```typescript
// server (router.ts)
import { initTRPC } from '@trpc/server';
const t = initTRPC.create();
export const appRouter = t.router({
user: t.procedure
.input(z.object({ id: z.number() }))
.query(async ({ input }) => {
const u = await db.user.findUnique({ where: { id: input.id } });
return u; // typed end-to-end
}),
});
// client — types inferred, no manual mapping
const { data } = trpc.user.useQuery({ id: 1 });
```
### 6. GraphQL Codegen
```yaml
# codegen.yml
schema: http://localhost:4000/graphql
documents: 'src/**/*.graphql'
generates:
src/gql/types.ts:
plugins:
- typescript
- typescript-operations
- typescript-react-query
```
### 7. View Model layer (UI formatting)
```typescript
type User = { firstName: string; lastName: string; createdAt: Date };
type UserVM = { fullName: string; joinedAgo: string };
function toVM(u: User): UserVM {
return {
fullName: `${u.firstName} ${u.lastName}`,
joinedAgo: formatDistanceToNow(u.createdAt, { addSuffix: true }),
};
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| REST + TypeScript | Zod schema 의 validate + transform at boundary. |
| Full-stack TypeScript monorepo | tRPC 의 zero transform overhead. |
| GraphQL backend | GraphQL Codegen 의 auto types. |
| Legacy snake_case API | humps 의 camelize at fetch boundary. |
| BigInt / Decimal | string serialization + parse on client. |
**기본값**: Zod schema 의 boundary validation + transform. tRPC 매 monorepo 의 ideal.
## 🔗 Graph
- 부모: [[Clean Architecture]] · [[API 설계]]
- 변형: [[Zod]] · [[tRPC]] · [[GraphQL Codegen]] · [[Adapter Pattern]]
- 응용: [[TanStack Query]] · [[React Hook Form]] · [[DTO Pattern]]
- Adjacent: [[직렬화 (Serialization)]] · [[Schema Validation]]
## 🤖 LLM 활용
**언제**: API integration, form submission, type-safe full-stack, validation at trust boundary.
**언제 X**: 매 internal tool 의 untyped — 매 still validate 매 trust boundary.
## ❌ 안티패턴
- **Trust the API blindly**: validate 매 trust boundary — server bug, version mismatch breaks UI silently.
- **Transform 의 component-level**: scatter mapping logic — centralize at fetch layer.
- **`any` types**: defeats TS — Zod infer 의 type derivation.
- **Date as string in app code**: lose type safety — parse to Date at boundary.
- **Manual mapping 의 100 fields**: codegen 의 use.
## 🧪 검증 / 중복
- Verified (Zod docs, tRPC docs, Martin Fowler "Patterns of Enterprise Application Architecture").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with Zod/tRPC/Codegen patterns |