kintex/mobile/lib/api.ts

113 lines
4.0 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 { getAttestationToken } from './integrity';
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}`;
// B2 앱 무결성 토큰(Play Integrity/App Attest) — 발급기 등록 시에만 첨부(미등록 시 null → 무해).
// 서버 검증 엔드포인트는 backend-dev 인계(_workspace/08_mobile_security_hardening.md).
if (!opts.anonymous) {
const attestation = await getAttestationToken();
if (attestation) headers['X-Integrity-Token'] = attestation;
}
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 }),
};