Files
2nd/10_Wiki/Topic_Programming/Coding/Web_Fetch_Wrapper_Design.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

4.6 KiB

id, title, category, status, source_trust_level, verification_status, created_at, updated_at, tags, tech_stack, applied_in, aliases
id title category status source_trust_level verification_status created_at updated_at tags tech_stack applied_in aliases
web-fetch-wrapper-design Fetch Wrapper 설계 — 인증 / 재시도 / 에러 정규화 Coding draft B conceptual 2026-05-09 2026-05-09
web
fetch
http-client
vibe-coding
language applicable_to
TypeScript / fetch
Web
Node
api client
axios alternative
ky
ofetch

Fetch Wrapper 설계

Raw fetch 직접 사용 = 매번 인증 / 에러 / 재시도 / 타임아웃 반복. 얇은 wrapper (또는 ofetch / ky) 가 표준. axios 도 옵션이지만 native fetch 가 가벼움.

📖 핵심 개념

  • 단일 baseUrl + 공통 헤더.
  • 자동 인증 헤더 + 401 → refresh.
  • 타임아웃 (AbortSignal.timeout).
  • 재시도 (backoff + retryable).
  • 에러 정규화 (status + body).

💻 코드 패턴

자체 wrapper

class APIError extends Error {
  constructor(public status: number, public body: any, message: string) {
    super(message);
  }
}

class APIClient {
  constructor(private baseUrl: string, private getToken: () => string | null) {}

  async request<T>(path: string, init: RequestInit & { timeout?: number; retries?: number } = {}): Promise<T> {
    const url = this.baseUrl + path;
    const { timeout = 10_000, retries = 2, ...rest } = init;

    const headers = new Headers(rest.headers);
    headers.set('Content-Type', 'application/json');
    const token = this.getToken();
    if (token) headers.set('Authorization', `Bearer ${token}`);

    let lastErr: unknown;
    for (let attempt = 0; attempt <= retries; attempt++) {
      try {
        const res = await fetch(url, {
          ...rest,
          headers,
          signal: rest.signal ?? AbortSignal.timeout(timeout),
        });
        if (res.ok) return await res.json();
        const body = await res.text();
        const err = new APIError(res.status, tryParse(body), `${res.status} ${path}`);
        if (this.isRetryable(res.status) && attempt < retries) {
          lastErr = err;
          await wait(200 * Math.pow(2, attempt) + Math.random() * 100);
          continue;
        }
        throw err;
      } catch (e) {
        if ((e as Error).name === 'AbortError') throw e;
        if (attempt === retries) throw e;
        lastErr = e;
        await wait(200 * Math.pow(2, attempt));
      }
    }
    throw lastErr;
  }

  private isRetryable(status: number) {
    return status === 408 || status === 429 || status >= 500;
  }

  get<T>(path: string, opts?: RequestInit): Promise<T> { return this.request<T>(path, { ...opts, method: 'GET' }); }
  post<T>(path: string, body: unknown): Promise<T> {
    return this.request<T>(path, { method: 'POST', body: JSON.stringify(body) });
  }
}

const api = new APIClient('https://api.example.com', () => getAccessToken());

ofetch / ky (라이브러리)

import { ofetch } from 'ofetch';

const $api = ofetch.create({
  baseURL: 'https://api.example.com',
  retry: 2,
  retryDelay: 200,
  retryStatusCodes: [408, 429, 500, 502, 503, 504],
  onRequest({ options }) {
    options.headers = { ...options.headers, Authorization: `Bearer ${getToken()}` };
  },
  async onResponseError({ response }) {
    if (response.status === 401) await refreshTokenAndRetry();
  },
});

const user = await $api<User>('/users/1');

Schema 검증 결합

import { z } from 'zod';
const UserS = z.object({ id: z.string(), email: z.string().email() });
type User = z.infer<typeof UserS>;

async function getUser(id: string): Promise<User> {
  const raw = await api.get<unknown>(`/users/${id}`);
  return UserS.parse(raw); // 응답 schema 보장
}

🤔 의사결정 기준

상황 도구
작은 프로젝트 직접 wrapper (50줄)
Vue / Nuxt ofetch (Nuxt 표준)
Node + 다양 옵션 ky 또는 undici
React + cache tanstack-query + 자체 fetch
GraphQL graphql-request 또는 Apollo
Streaming (LLM) fetch + ReadableStream 직접

안티packs턴

  • fetch 매번 직접: 인증 / 에러 / 재시도 매번 작성.
  • 에러를 throw 안 함: if (!res.ok) 무시 → 빈 body 처리.
  • JSON 자동 parse 가정: 4xx body 가 HTML 일 수도. content-type 확인.
  • AbortSignal 누락: 떠난 페이지의 요청 계속.
  • 401 무한 retry: refresh 한 번만 시도.
  • 재시도 시 같은 idempotency key 또는 키 없음: 중복 처리 위험.
  • 응답 schema 검증 X: API 형식 변경 시 silent.

🤖 LLM 활용 힌트

  • 직접 wrapper 50줄 또는 ofetch.
  • 응답 = zod schema 검증 + brand.

🔗 관련 문서