mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-23 23:09:20 +08:00
65 lines
1.7 KiB
TypeScript
65 lines
1.7 KiB
TypeScript
import { ExtensionError } from '@/shared/errors';
|
||
import { getSettings } from '@/storage/settings';
|
||
|
||
export interface ApiResponseBody<T> {
|
||
code: number;
|
||
message: string;
|
||
data: T;
|
||
}
|
||
|
||
/** 在扩展上下文(Background / Popup)内直连 Open API */
|
||
export async function executeOpenApiFetch<T>(
|
||
path: string,
|
||
init: RequestInit = {},
|
||
): Promise<T> {
|
||
const settings = await getSettings();
|
||
if (!settings.apiBaseUrl) {
|
||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Base URL');
|
||
}
|
||
if (!settings.apiKey) {
|
||
throw new ExtensionError('CONFIG_MISSING', '请先配置 BI Open API Key');
|
||
}
|
||
|
||
const url = `${settings.apiBaseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
||
const headers = new Headers(init.headers);
|
||
headers.set('Content-Type', 'application/json');
|
||
headers.set('X-Api-Key', settings.apiKey);
|
||
|
||
let response: Response;
|
||
try {
|
||
response = await fetch(url, {
|
||
...init,
|
||
headers,
|
||
});
|
||
} catch {
|
||
throw new ExtensionError('NETWORK_ERROR', '网络异常,无法连接 BI Open API');
|
||
}
|
||
|
||
if (response.status === 401) {
|
||
throw new ExtensionError('AUTH_FAILED', 'API Key 无效、过期或 IP 不在白名单');
|
||
}
|
||
|
||
let body: ApiResponseBody<T>;
|
||
try {
|
||
body = (await response.json()) as ApiResponseBody<T>;
|
||
} catch {
|
||
throw new ExtensionError('API_REQUEST_FAILED', `请求失败(HTTP ${response.status})`);
|
||
}
|
||
|
||
if (!response.ok) {
|
||
throw new ExtensionError(
|
||
'API_REQUEST_FAILED',
|
||
body.message || `请求失败(HTTP ${response.status})`,
|
||
);
|
||
}
|
||
|
||
if (body.code !== 0 && body.code !== 200) {
|
||
throw new ExtensionError(
|
||
'API_BUSINESS_ERROR',
|
||
body.message || `业务错误(code=${body.code})`,
|
||
);
|
||
}
|
||
|
||
return body.data;
|
||
}
|