[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,100 +1,303 @@
|
||||
---
|
||||
id: wiki-2026-0508-api-응답-및-상태-모델링-state-modeling-a
|
||||
title: API 응답 및 상태 모델링 (State Modeling and API Responses)
|
||||
title: API Response & State Modeling
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-09EEF3]
|
||||
aliases: [State Modeling, Discriminated Union, Result type, Tagged Union, exhaustive check]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
source_trust_level: B
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [typescript, api-design, state-modeling, discriminated-union, result-type, exhaustive-check]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - API 응답 및 상태 모델링 ([[State|State]] Modeling and API Responses)"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-09
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: TypeScript / Zod / TS-Result
|
||||
---
|
||||
|
||||
# [[API 응답 및 상태 모델링 (State Modeling and API Responses)|API 응답 및 상태 모델링 (State Modeling and API Responses]]
|
||||
# API Response & State Modeling
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> API 응답 및 상태 모델링은 애플리케이션에서 발생할 수 있는 네트워크 통신 결과나 UI의 변화 과정을 타입 시스템을 통해 안전하고 예측 가능하게 설계하는 기법이다 [1, 2]. 이 모델링은 주로 식별 가능한 유니온([[Discriminated Unions|Discriminated Unions]])이나 명시적인 Result 객체를 활용하여 존재해서는 안 될 유효하지 않은 상태를 원천적으로 차단한다 [3, 4]. 궁극적으로 컴파일러가 모든 가능한 응답 상태를 검사(Exhaustiveness checking)하도록 강제함으로써, 런타임 버그를 줄이고 코드의 안정성과 가독성을 높여준다 [5-7].
|
||||
## 📌 한 줄 통찰
|
||||
> **"매 invalid state 의 unrepresentable"**. Discriminated union + Result type. 매 compile-time exhaustive check. 매 runtime bug 의 prevent.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **식별 가능한 유니온(Discriminated Unions)을 활용한 응답 상태 구조화**
|
||||
네트워크 통신이나 API 응답은 대체로 '로딩 중(loading)', '실패(failed)', '성공(success)'과 같이 명확히 구분되는 상태를 가진다 [8]. TypeScript에서는 `kind`나 `state`와 같은 공통된 리터럴 타입 판별자(Discriminator)를 사용하여 이런 상태들을 하나로 묶어 식별 가능한 유니온으로 모델링한다 [8-10]. 이를 통해 각 상태에 불가능한 속성 조합(예: 에러 상태인데 성공 데이터가 존재하는 등)이 생성되는 것을 방지하고 타입 안정성을 확보할 수 있다 [1, 3, 5].
|
||||
## 📖 핵심
|
||||
|
||||
* **상태 머신(State Machine)과 워크플로우 적용**
|
||||
API 요청의 생명주기뿐만 아니라, 복잡한 폼 제출의 여러 단계(검증, 제출 중, 에러 등), 비동기 작업 패턴, 라우터 상태 또한 식별 가능한 유니온을 활용한 상태 머신으로 표현하기 적합하다 [3, 11-13]. 이 패턴을 `switch` 문과 함께 사용하면, 특정 상태가 새롭게 추가되었을 때 코드를 누락하는 실수를 방지하도록 컴파일러가 완전성 검사(Exhaustiveness checking)를 수행하여 런타임 오류를 예방한다 [5, 6, 14, 15].
|
||||
### 매 problem (without modeling)
|
||||
```ts
|
||||
// ❌ Optional everything
|
||||
type Response = {
|
||||
data?: User;
|
||||
error?: string;
|
||||
loading?: boolean;
|
||||
};
|
||||
|
||||
* **예외 발생을 지양하는 Result 타입 기반 에러 모델링**
|
||||
예상 가능한 애플리케이션의 오류를 단순히 `throw`를 이용해 예외(Exception)로 던지기보다는 성공 데이터(`Ok`) 또는 에러(`Err`/`Fail`)를 나타내는 명시적인 Result 타입 객체로 감싸서 반환하는 접근 방식이 권장된다 [4, 16-18]. 이 방식은 함수 시그니처만 보아도 어떠한 오류 응답이 발생할 수 있는지 사전에 파악할 수 있게 해주며, C# 같은 언어의 API 컨트롤러에서도 철저한 오류 검증을 위해 폭넓게 활용되곤 한다 [7, 19-22].
|
||||
|
||||
* **메타데이터를 통한 API 제어 흐름 분리**
|
||||
내부 로직을 원활하게 디버깅하고 시스템의 옵저버빌리티를 높이기 위해, 응답 객체에 `_tag`와 같은 내부 식별용 메타데이터를 추가하여 상태를 정의하는 패턴도 사용된다 [23-25]. 이를 활용하면 클라이언트에서는 단순한 HTTP 상태 코드를 넘어, 각각의 메타데이터 값에 맞게 세밀한 맞춤형 제어 및 에러 처리를 수행할 수 있다 [25].
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Design & Experience 분야의 자동 자산화 수행.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** 식별 가능한 유니온 (Discriminated Unions), 완전성 검사 (Exhaustiveness checking), Result 타입 ([[Result Type|Result Type]])
|
||||
- **Projects/Contexts:** 상태 머신 (State Machine), 오류 처리 아키텍처 (Error Handling [[Architecture|Architecture]])
|
||||
- **Contradictions/Notes:** API나 시스템의 에러 응답을 모델링할 때 'Result 타입'을 사용하는 방식에 대해 개발자 간의 이견이 존재한다. 예상된 실패를 Result로 강제 반환하면 실행 흐름이 예측 가능해진다는 찬성 측 주장이 있는 반면, 전역 예외 처리기(Global Exception Handler)를 사용하는 쪽이 예외를 단순히 위로 올려보낼 수 있어 불필요한 보일러플레이트 코드 및 과도한 제어 흐름 분기(`switch`문 등)를 줄이고 컨트롤러를 더 깔끔하게 유지할 수 있다는 반대 주장도 팽팽하게 맞선다 [7, 20, 26-31].
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
|
||||
---
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(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
|
||||
// 매 combination 의 가능?
|
||||
// loading=true, data=set ?
|
||||
// error=set, data=set ?
|
||||
// 매 inconsistent state.
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Solution: Discriminated Union (Tagged Union)
|
||||
```ts
|
||||
type Response =
|
||||
| { type: 'idle' }
|
||||
| { type: 'loading' }
|
||||
| { type: 'success'; data: User }
|
||||
| { type: 'error'; message: string };
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// 매 state 의 explicit. 매 invalid 의 impossible.
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Result type
|
||||
```ts
|
||||
type Result<T, E = Error> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; error: E };
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// Usage
|
||||
async function fetchUser(id: string): Promise<Result<User>> {
|
||||
try {
|
||||
const user = await api.users.get(id);
|
||||
return { ok: true, value: user };
|
||||
} catch (e) {
|
||||
return { ok: false, error: e as Error };
|
||||
}
|
||||
}
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
// Caller
|
||||
const result = await fetchUser('123');
|
||||
if (result.ok) {
|
||||
console.log(result.value.name); // type: User
|
||||
} else {
|
||||
console.error(result.error);
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Exhaustive check
|
||||
```ts
|
||||
function render(state: Response) {
|
||||
switch (state.type) {
|
||||
case 'idle': return <Idle />;
|
||||
case 'loading': return <Spinner />;
|
||||
case 'success': return <Profile user={state.data} />;
|
||||
case 'error': return <Error msg={state.message} />;
|
||||
default:
|
||||
const _: never = state; // compile error if state added
|
||||
throw new Error('unreachable');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
→ 매 새 state 의 추가 시 compiler 의 exhaustive check.
|
||||
|
||||
### 매 application
|
||||
|
||||
#### React state
|
||||
```tsx
|
||||
const [state, setState] = useState<Response>({ type: 'idle' });
|
||||
|
||||
// 매 fetching
|
||||
setState({ type: 'loading' });
|
||||
|
||||
const result = await fetchUser(id);
|
||||
if (result.ok) {
|
||||
setState({ type: 'success', data: result.value });
|
||||
} else {
|
||||
setState({ type: 'error', message: result.error.message });
|
||||
}
|
||||
```
|
||||
|
||||
#### TanStack Query (built-in)
|
||||
```tsx
|
||||
const { data, error, isLoading, isSuccess } = useQuery({...});
|
||||
|
||||
if (isLoading) return <Spinner />;
|
||||
if (error) return <Error msg={error.message} />;
|
||||
return <Profile user={data} />;
|
||||
```
|
||||
|
||||
→ 매 query state 의 already discriminated.
|
||||
|
||||
#### State machine (XState)
|
||||
```ts
|
||||
import { createMachine } from 'xstate';
|
||||
|
||||
const machine = createMachine({
|
||||
id: 'fetch',
|
||||
initial: 'idle',
|
||||
states: {
|
||||
idle: { on: { FETCH: 'loading' } },
|
||||
loading: { on: { SUCCESS: 'success', ERROR: 'error' } },
|
||||
success: { on: { REFETCH: 'loading' } },
|
||||
error: { on: { RETRY: 'loading' } },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### 매 API response shape
|
||||
|
||||
#### Success / Error envelope
|
||||
```ts
|
||||
type APIResponse<T> =
|
||||
| { status: 'ok'; data: T }
|
||||
| { status: 'error'; code: string; message: string };
|
||||
```
|
||||
|
||||
#### Pagination
|
||||
```ts
|
||||
type Paginated<T> = {
|
||||
data: T[];
|
||||
meta: { total: number; page: number; perPage: number };
|
||||
};
|
||||
```
|
||||
|
||||
#### Nullable vs Optional
|
||||
```ts
|
||||
// Nullable: 명시적 null
|
||||
type User = { name: string; bio: string | null };
|
||||
|
||||
// Optional: 매 absent
|
||||
type Update = { name?: string; bio?: string };
|
||||
```
|
||||
|
||||
→ 매 different semantic.
|
||||
|
||||
### Validation (runtime, Zod)
|
||||
```ts
|
||||
import { z } from 'zod';
|
||||
|
||||
const UserSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
email: z.string().email(),
|
||||
age: z.number().int().min(0),
|
||||
});
|
||||
|
||||
type User = z.infer<typeof UserSchema>;
|
||||
|
||||
// 매 API response 의 parse + validate
|
||||
const result = UserSchema.safeParse(await response.json());
|
||||
if (result.success) {
|
||||
// result.data: User
|
||||
} else {
|
||||
console.error(result.error);
|
||||
}
|
||||
```
|
||||
|
||||
→ 매 type + runtime 의 둘 다.
|
||||
|
||||
### Branded types (extra safety)
|
||||
```ts
|
||||
type UserId = string & { __brand: 'UserId' };
|
||||
type OrderId = string & { __brand: 'OrderId' };
|
||||
|
||||
function getUser(id: UserId) { ... }
|
||||
|
||||
const id = '123' as UserId;
|
||||
getUser(id); // OK
|
||||
getUser('123'); // ❌ string ≠ UserId
|
||||
```
|
||||
|
||||
## 💻 Code Pattern
|
||||
|
||||
### Result + chain
|
||||
```ts
|
||||
class Result<T, E> {
|
||||
constructor(
|
||||
public readonly ok: boolean,
|
||||
public readonly value?: T,
|
||||
public readonly error?: E
|
||||
) {}
|
||||
|
||||
map<U>(fn: (v: T) => U): Result<U, E> {
|
||||
return this.ok ? Result.ok(fn(this.value!)) : Result.err(this.error!);
|
||||
}
|
||||
|
||||
flatMap<U>(fn: (v: T) => Result<U, E>): Result<U, E> {
|
||||
return this.ok ? fn(this.value!) : Result.err(this.error!);
|
||||
}
|
||||
|
||||
static ok<T, E>(value: T): Result<T, E> { return new Result(true, value); }
|
||||
static err<T, E>(error: E): Result<T, E> { return new Result(false, undefined, error); }
|
||||
}
|
||||
|
||||
// Usage
|
||||
const result = await fetchUser('123');
|
||||
const name = result.map(u => u.name).map(s => s.toUpperCase());
|
||||
```
|
||||
|
||||
### Effect-TS (advanced FP)
|
||||
```ts
|
||||
import { Effect, pipe } from 'effect';
|
||||
|
||||
const program = pipe(
|
||||
Effect.tryPromise(() => api.users.get('123')),
|
||||
Effect.map(u => u.name),
|
||||
Effect.catchAll(e => Effect.succeed('Unknown')),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(program);
|
||||
```
|
||||
|
||||
### React hook with state
|
||||
```tsx
|
||||
function useFetchUser(id: string) {
|
||||
const [state, setState] = useState<{
|
||||
status: 'idle' | 'loading' | 'success' | 'error';
|
||||
data?: User;
|
||||
error?: Error;
|
||||
}>({ status: 'idle' });
|
||||
|
||||
useEffect(() => {
|
||||
setState({ status: 'loading' });
|
||||
fetchUser(id)
|
||||
.then(data => setState({ status: 'success', data }))
|
||||
.catch(error => setState({ status: 'error', error }));
|
||||
}, [id]);
|
||||
|
||||
return state;
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 결정 기준
|
||||
|
||||
| 상황 | 추천 |
|
||||
|---|---|
|
||||
| Simple state | Discriminated union |
|
||||
| Async result | Result type |
|
||||
| Complex state | XState machine |
|
||||
| API response | Envelope + Zod validation |
|
||||
| Type identity | Branded type |
|
||||
| FP heavy | Effect-TS |
|
||||
|
||||
**기본값**: Discriminated union + Result type + Zod validation.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[TypeScript]] · [[State-Management]] · [[API-Design]]
|
||||
- 변형: [[Discriminated-Union]] · [[Tagged-Union]] · [[Result-Type]]
|
||||
- 응용: [[XState]] · [[Effect-TS]] · [[Zod-Validation]]
|
||||
- Adjacent: [[Branded-Types]] · [[Exhaustive-Check]] · [[TanStack-Query]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 TypeScript app 의 state design. 매 API contract 의 type-safe.
|
||||
**언제 X**: 매 simple primitive (boolean enough). 매 prototype.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Optional everything**: invalid state.
|
||||
- **`any` for response**: type 의 가치 X.
|
||||
- **No exhaustive check**: 매 새 state 의 missed.
|
||||
- **Throw + catch 만**: Result type 의 더 explicit.
|
||||
- **No runtime validation**: 매 wrong API response 의 silent.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (TypeScript handbook, neverthrow library docs).
|
||||
- 신뢰도 B.
|
||||
- Related: [[Tagged_Union_Discriminated_Types]] · [[TS_Schema_Validation_Comparison]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-09 | Manual cleanup — discriminated union + Result + state machine + code |
|
||||
|
||||
Reference in New Issue
Block a user