233 lines
8.0 KiB
TypeScript
233 lines
8.0 KiB
TypeScript
/**
|
||
* shared/api/client.ts
|
||
* 跨域 HTTP 客户端:envelope 解析、BusinessError、requestJson、requestBlob。
|
||
* 依赖:auth、vue-i18n、shared/utils/download(Content-Disposition 文件名)。
|
||
* 所有 feature API 层应通过此模块发起请求;二进制下载走 requestBlob,失败仍为 BusinessError。
|
||
*/
|
||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||
import { parseContentDispositionFilename } from '@/shared/utils/download';
|
||
import i18n from '@/i18n';
|
||
|
||
export interface ApiSuccessEnvelope<T> {
|
||
success: true;
|
||
data: T;
|
||
request_id?: string;
|
||
timestamp?: string;
|
||
}
|
||
|
||
export interface ApiErrorBody {
|
||
code?: string;
|
||
message?: string;
|
||
details?: Record<string, any>;
|
||
retryable?: boolean;
|
||
}
|
||
|
||
export interface ApiErrorEnvelope {
|
||
success: false;
|
||
error?: ApiErrorBody;
|
||
request_id?: string;
|
||
timestamp?: string;
|
||
}
|
||
|
||
export class BusinessError extends Error {
|
||
code: string;
|
||
details: Record<string, any>;
|
||
requestId?: string;
|
||
status?: number;
|
||
|
||
constructor(args: { message: string; code?: string; details?: Record<string, any>; 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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按错误码解析当前语言文案,供 requestJson 与认证二进制下载共用。
|
||
* @param code - 后端 AppError 机器码
|
||
* @param fallbackMessage - 未配置错误码时的后端说明
|
||
* @returns 当前语言的用户可见错误信息
|
||
*/
|
||
export function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
|
||
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;
|
||
};
|
||
|
||
/**
|
||
* 在 errors.codes 中查找文案:优先字面量键(含点号),再尝试下划线键与路径解析。
|
||
*/
|
||
const lookupCodeMessage = (rawCode: string): string | null => {
|
||
const bag = i18n.global.tm('errors.codes') as Record<string, unknown> | string | null;
|
||
if (bag && typeof bag === 'object' && !Array.isArray(bag)) {
|
||
const direct = bag[rawCode];
|
||
if (typeof direct === 'string' && direct.trim()) return direct;
|
||
const underscoredLeaf = rawCode.replace(/\./g, '_');
|
||
const viaUnderscore = bag[underscoredLeaf];
|
||
if (typeof viaUnderscore === 'string' && viaUnderscore.trim()) return viaUnderscore;
|
||
}
|
||
const underscoredPath = `errors.codes.${rawCode.replace(/\./g, '_')}`;
|
||
if (i18n.global.te(underscoredPath)) return String(i18n.global.t(underscoredPath));
|
||
const dottedPath = `errors.codes.${rawCode}`;
|
||
if (i18n.global.te(dottedPath)) return String(i18n.global.t(dottedPath));
|
||
return null;
|
||
};
|
||
|
||
if (code) {
|
||
const localized = lookupCodeMessage(code);
|
||
if (localized) {
|
||
const normalizedCode = code.replace(/\./g, '_');
|
||
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<any> | 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<T>(url: string, init?: RequestInit): Promise<T> {
|
||
const headers = new Headers(init?.headers || {});
|
||
const authHeaders = getAuthHeaders();
|
||
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
|
||
// 带 body 的请求若未显式声明类型,统一补 JSON 头:否则 Flask get_json(silent=True)
|
||
// 会因 Content-Type 非 JSON 解析出 None,把有效载荷当空 body 处理(如订单交期回复保存被误判 400)。
|
||
if (init?.body && !headers.has('Content-Type')) {
|
||
headers.set('Content-Type', 'application/json');
|
||
}
|
||
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;
|
||
}
|
||
|
||
export type BlobDownloadResult = {
|
||
blob: Blob;
|
||
filename?: string;
|
||
requestId?: string;
|
||
};
|
||
|
||
/**
|
||
* 发起需鉴权的二进制下载;失败时按 Envelope 解析为 BusinessError(与 requestJson 同源)。
|
||
* @param url - 请求路径
|
||
* @param init - fetch 初始化参数
|
||
* @returns blob 与可选文件名、request_id
|
||
*/
|
||
export async function requestBlob(url: string, init?: RequestInit): Promise<BlobDownloadResult> {
|
||
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 });
|
||
const requestIdHeader = res.headers.get('X-Request-Id') || undefined;
|
||
const contentType = (res.headers.get('Content-Type') || '').toLowerCase();
|
||
|
||
if (!res.ok) {
|
||
let data: any = null;
|
||
if (contentType.includes('application/json')) {
|
||
try {
|
||
data = await res.json();
|
||
} catch {
|
||
data = null;
|
||
}
|
||
}
|
||
if (data && 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 || requestIdHeader,
|
||
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 || requestIdHeader,
|
||
status: res.status,
|
||
});
|
||
}
|
||
|
||
const blob = await res.blob();
|
||
return {
|
||
blob,
|
||
filename: parseContentDispositionFilename(res.headers.get('Content-Disposition')),
|
||
requestId: requestIdHeader,
|
||
};
|
||
}
|