/** * shared/api/client.ts * 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson。 * 所有 feature API 层应通过此模块发起 JSON 请求。 */ import { getAuthHeaders } from '@/shared/utils/auth'; import i18n from '@/i18n'; export interface ApiSuccessEnvelope { success: true; data: T; request_id?: string; timestamp?: string; } export interface ApiErrorBody { code?: string; message?: string; details?: Record; retryable?: boolean; } export interface ApiErrorEnvelope { success: false; error?: ApiErrorBody; request_id?: string; timestamp?: string; } export class BusinessError extends Error { code: string; details: Record; requestId?: string; status?: number; constructor(args: { message: string; code?: string; details?: Record; requestId?: string; status?: number }) { super(args.message); this.name = 'BusinessError'; this.code = args.code || 'SYSTEM.UNKNOWN'; this.details = args.details || {}; this.requestId = args.requestId; this.status = args.status; } } function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string { const normalizedCode = code ? code.replace(/\./g, '_') : ''; const key = normalizedCode ? `errors.codes.${normalizedCode}` : ''; const fallback = String(fallbackMessage || '').trim(); const isGenericFallback = (msg: string) => { const v = msg.trim().toLowerCase(); if (!v) return true; if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true; if (v === 'request failed' || v === 'request failed.') return true; if (v.startsWith('http ')) return true; return false; }; if (key && i18n.global.te(key)) { const localized = String(i18n.global.t(key)); if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) { return `${localized} ${fallback}`; } if ( normalizedCode === 'AUTH_FORBIDDEN' && fallback && !isGenericFallback(fallback) && fallback.toLowerCase() !== 'forbidden' && fallback !== localized ) { return fallback; } return localized; } if (fallback) return fallback; if (i18n.global.te('errors.generic')) { return String(i18n.global.t('errors.generic')); } return code || 'Request failed'; } export const isEnvelope = (payload: any): payload is ApiSuccessEnvelope | ApiErrorEnvelope => { return !!payload && typeof payload === 'object' && typeof payload.success === 'boolean'; }; function pickLegacyErrorMessage(payload: any): string | undefined { if (!payload) return undefined; if (typeof payload.error === 'string' && payload.error.trim()) return payload.error; if (typeof payload.message === 'string' && payload.message.trim()) return payload.message; return undefined; } export async function requestJson(url: string, init?: RequestInit): Promise { const headers = new Headers(init?.headers || {}); const authHeaders = getAuthHeaders(); Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string)); const res = await fetch(url, { ...init, headers }); let data: any = null; try { data = await res.json(); } catch { if (!res.ok) { throw new BusinessError({ message: `HTTP ${res.status}`, code: 'SYSTEM.HTTP_ERROR', status: res.status, }); } return null as T; } if (!res.ok) { if (isEnvelope(data) && data.success === false) { throw new BusinessError({ message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`), code: data.error?.code, details: data.error?.details, requestId: data.request_id, status: res.status, }); } throw new BusinessError({ message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`), code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR', details: data?.details || {}, requestId: data?.request_id, status: res.status, }); } if (isEnvelope(data)) { if (data.success === true) return data.data as T; throw new BusinessError({ message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || 'Request failed'), code: data.error?.code, details: data.error?.details, requestId: data.request_id, status: res.status, }); } return data as T; }