Files
2nd/10_Wiki/Topic_Programming/AI_and_ML/API 응답 및 상태 모델링 (State Modeling and API Responses).md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

7.2 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-api-응답-및-상태-모델링-state-modeling-a API Response & State Modeling 10_Wiki/Topics verified self
State Modeling
Discriminated Union
Result type
Tagged Union
exhaustive check
none B 0.9 applied
typescript
api-design
state-modeling
discriminated-union
result-type
exhaustive-check
2026-05-09 pending
language framework
TypeScript TypeScript / Zod / TS-Result

API Response & State Modeling

📌 한 줄 통찰

"매 invalid state 의 unrepresentable". Discriminated union + Result type. 매 compile-time exhaustive check. 매 runtime bug 의 prevent.

📖 핵심

매 problem (without modeling)

// ❌ Optional everything
type Response = {
  data?: User;
  error?: string;
  loading?: boolean;
};

// 매 combination 의 가능?
// loading=true, data=set ?
// error=set, data=set ?
// 매 inconsistent state.

Solution: Discriminated Union (Tagged Union)

type Response =
  | { type: 'idle' }
  | { type: 'loading' }
  | { type: 'success'; data: User }
  | { type: 'error'; message: string };

// 매 state 의 explicit. 매 invalid 의 impossible.

Result type

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

// 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 };
  }
}

// Caller
const result = await fetchUser('123');
if (result.ok) {
  console.log(result.value.name);   // type: User
} else {
  console.error(result.error);
}

Exhaustive check

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

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)

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)

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

type APIResponse<T> = 
  | { status: 'ok'; data: T }
  | { status: 'error'; code: string; message: string };

Pagination

type Paginated<T> = {
  data: T[];
  meta: { total: number; page: number; perPage: number };
};

Nullable vs Optional

// Nullable: 명시적 null
type User = { name: string; bio: string | null };

// Optional: 매 absent
type Update = { name?: string; bio?: string };

→ 매 different semantic.

Validation (runtime, Zod)

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)

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

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)

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

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

🤖 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.

🧪 검증 / 중복

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-09 Manual cleanup — discriminated union + Result + state machine + code