fix(web): 修复生产环境 API 不可用误报
This commit is contained in:
@@ -1,4 +1,14 @@
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1';
|
||||
type ApiEnv = {
|
||||
NEXT_PUBLIC_API_URL?: string;
|
||||
NODE_ENV?: string;
|
||||
};
|
||||
|
||||
export function resolveApiBase(env: ApiEnv = process.env) {
|
||||
const fallback = env.NODE_ENV === 'production' ? '/api/v1' : 'http://localhost:3001/api/v1';
|
||||
return (env.NEXT_PUBLIC_API_URL || fallback).replace(/\/$/, '');
|
||||
}
|
||||
|
||||
const API_BASE = resolveApiBase();
|
||||
|
||||
let apiAvailable: boolean | null = null;
|
||||
let probePromise: Promise<boolean> | null = null;
|
||||
@@ -23,17 +33,19 @@ export class ApiRequestError extends Error {
|
||||
}
|
||||
|
||||
async function checkApi(): Promise<boolean> {
|
||||
if (apiAvailable !== null) return apiAvailable;
|
||||
if (apiAvailable === true) return true;
|
||||
if (probePromise) return probePromise;
|
||||
probePromise = (async () => {
|
||||
try {
|
||||
// 探测一个不依赖数据库的端点(/config/ai 总是返回 200,只要 NestJS 起来了)
|
||||
const res = await fetch(`${API_BASE}/config/ai`, { method: 'GET', signal: AbortSignal.timeout(1500) });
|
||||
apiAvailable = res.ok;
|
||||
apiAvailable = res.ok ? true : null;
|
||||
} catch {
|
||||
apiAvailable = false;
|
||||
apiAvailable = null;
|
||||
} finally {
|
||||
probePromise = null;
|
||||
}
|
||||
return apiAvailable;
|
||||
return apiAvailable === true;
|
||||
})();
|
||||
return probePromise;
|
||||
}
|
||||
@@ -45,7 +57,10 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
...options,
|
||||
}).catch(() => null);
|
||||
if (!res) throw new Error('API 不可用');
|
||||
if (!res) {
|
||||
apiAvailable = null;
|
||||
throw new Error('API 不可用');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({}));
|
||||
throw new ApiRequestError(res.status, error);
|
||||
@@ -83,3 +98,8 @@ export const api = {
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export function __resetApiAvailabilityForTests() {
|
||||
apiAvailable = null;
|
||||
probePromise = null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user