kintex/mobile/lib/api.ts
zio 6c9891c7e2 feat: mobile harness + design v2.1 (84 screens) + PLANNING v3.1 + deliverables + Stitch screens
- Harness: kintex-mobile-dev agent + kintex-mobile-orchestrator skill (WISE mobile ref, Stitch-first design rule, dual app targets B2B/B2C)
- design.md v2.1: full 84-screen inventory (web 51 / admin 10 / public 8 / mobile 15) with Stitch prompts incl. ticketing (SCR-P7/P8, M14/M15)
- PLANNING v3.1: unified account + split signup tracks (2FA required for staff, light signup/guest for visitors), one codebase / two app targets
- Deliverables: dev plan (21s), user/operator/developer guides (17/14/15s), program spec (44s, 65 programs, 8 flowcharts), DA (DB design 14s + table spec xlsx 35 tables/299 cols)
- Benchmark: ticketing-app-benchmark.md (7 apps) -> IMPLEMENTATION_BACKLOG Phase F (14 items)
- Stitch: 23 generated screens saved (mobile 10, admin 6, web core 5, ticket 2)
- mobile/: Expo scaffold (SDK 51, expo-router, secure store JWT)
- frontend: SCR-13~17 QA fixes, icons.tsx, kintexEvents, V10 seed migration
- ci/: KINTEX CI logo assets

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 23:31:45 +09:00

105 lines
3.5 KiB
TypeScript

/*
* API 클라이언트 — 백엔드 계약 base URL·JWT 헤더·오류 봉투(success/data/error) 처리.
* 근거: _workspace/01_backend_contracts.md §0 (ApiResponse 봉투, 오류 코드→HTTP, 인증 헤더).
* 웹 프론트(src/frontend/src/api/client.ts) 패턴과 정합. 시크릿 하드코딩 없음.
*/
import { API_BASE } from './config';
import type { ApiError, ApiErrorCode, ApiResponse } from './types';
/** 봉투 error를 그대로 던지는 오류 타입 — UI는 code로 분기(OTP_REQUIRED·COMPLIANCE_BLOCKED 등). */
export class ApiRequestError extends Error {
readonly code: ApiErrorCode | 'NETWORK' | 'UNKNOWN';
readonly httpStatus: number;
constructor(code: ApiRequestError['code'], message: string, httpStatus: number) {
super(message);
this.name = 'ApiRequestError';
this.code = code;
this.httpStatus = httpStatus;
}
}
/** 서버 미구현(501/NOT_IMPLEMENTED)·네트워크 장애 등 폴백(degraded) 판정 헬퍼. */
export function isDegraded(e: unknown): boolean {
if (!(e instanceof ApiRequestError)) return false;
return (
e.code === 'NETWORK' ||
e.code === 'NOT_IMPLEMENTED' ||
e.code === 'INTERNAL' ||
e.httpStatus === 501 ||
e.httpStatus >= 502
);
}
// ── 메모리 내 액세스 토큰 (영속은 AuthContext가 secure-store로 관리) ──
let accessToken: string | null = null;
export function setAccessToken(token: string | null): void {
accessToken = token;
}
export function getAccessToken(): string | null {
return accessToken;
}
interface RequestOptions {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
body?: unknown;
signal?: AbortSignal;
/** 인증 헤더 생략(공개 경로: login·register·forgot·reset·health). */
anonymous?: boolean;
}
async function request<T>(path: string, opts: RequestOptions = {}): Promise<T> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (!opts.anonymous && accessToken) headers.Authorization = `Bearer ${accessToken}`;
let res: Response;
try {
res = await fetch(`${API_BASE}${path}`, {
method: opts.method ?? 'GET',
headers,
body: opts.body != null ? JSON.stringify(opts.body) : undefined,
signal: opts.signal,
});
} catch (e) {
if ((e as Error).name === 'AbortError') throw e;
throw new ApiRequestError('NETWORK', '네트워크 연결을 확인해 주세요.', 0);
}
if (res.status === 401) {
// 토큰 만료/무효 — 메모리 토큰 정리 (라우터가 로그인으로 유도)
accessToken = null;
}
let payload: ApiResponse<T> | null = null;
const text = await res.text();
if (text) {
try {
payload = JSON.parse(text) as ApiResponse<T>;
} catch {
payload = null;
}
}
if (!res.ok || (payload && payload.success === false)) {
const err: ApiError | null = payload?.error ?? null;
throw new ApiRequestError(
(err?.code as ApiErrorCode) ?? 'UNKNOWN',
err?.message ?? `요청을 처리하지 못했습니다. (${res.status})`,
res.status,
);
}
if (!payload) {
return undefined as unknown as T;
}
return payload.data as T;
}
export const api = {
get: <T>(path: string, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
request<T>(path, { ...opts, method: 'GET' }),
post: <T>(path: string, body?: unknown, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
request<T>(path, { ...opts, method: 'POST', body }),
put: <T>(path: string, body?: unknown, opts?: Omit<RequestOptions, 'method' | 'body'>) =>
request<T>(path, { ...opts, method: 'PUT', body }),
};