113 lines
3.1 KiB
TypeScript
113 lines
3.1 KiB
TypeScript
let apiBase = "";
|
||
let preparing: Promise<void> | null = null;
|
||
let deepScanDone = false;
|
||
|
||
type UnauthorizedHandler = () => void;
|
||
let unauthorizedHandler: UnauthorizedHandler | null = null;
|
||
let unauthorizedNotified = false;
|
||
|
||
export function setUnauthorizedHandler(handler: UnauthorizedHandler | null) {
|
||
unauthorizedHandler = handler;
|
||
}
|
||
|
||
export function clearUnauthorized() {
|
||
unauthorizedNotified = false;
|
||
}
|
||
|
||
function notifyUnauthorized() {
|
||
if (unauthorizedNotified) return;
|
||
unauthorizedNotified = true;
|
||
unauthorizedHandler?.();
|
||
}
|
||
|
||
export class ApiError extends Error {
|
||
status: number;
|
||
|
||
constructor(status: number, message: string) {
|
||
super(message);
|
||
this.name = "ApiError";
|
||
this.status = status;
|
||
}
|
||
}
|
||
|
||
export function initApi(): Promise<void> {
|
||
if (!preparing) {
|
||
preparing = resolveApiBase().catch((error: unknown) => {
|
||
preparing = null;
|
||
throw error;
|
||
});
|
||
}
|
||
return preparing;
|
||
}
|
||
|
||
async function resolveApiBase(): Promise<void> {
|
||
if (!("__TAURI_INTERNALS__" in window)) return;
|
||
const { invoke } = await import("@tauri-apps/api/core");
|
||
const attempts = deepScanDone ? 1 : 50;
|
||
deepScanDone = true;
|
||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||
try {
|
||
const port = await invoke<number>("backend_port");
|
||
if (port > 0) {
|
||
apiBase = `http://127.0.0.1:${port}`;
|
||
return;
|
||
}
|
||
} catch {
|
||
// 窗口可能比端口命令更早就绪。
|
||
}
|
||
if (attempt + 1 < attempts) {
|
||
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||
}
|
||
}
|
||
throw new ApiError(0, "连接失败");
|
||
}
|
||
|
||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||
await initApi();
|
||
let response: Response;
|
||
try {
|
||
const headers = new Headers(init?.headers);
|
||
if (init?.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
|
||
headers.set("Content-Type", "application/json");
|
||
}
|
||
response = await fetch(`${apiBase}${path}`, { ...init, headers });
|
||
} catch {
|
||
throw new ApiError(0, "连接失败");
|
||
}
|
||
const text = await response.text();
|
||
let data: { detail?: unknown } | null = null;
|
||
if (text) {
|
||
try {
|
||
data = JSON.parse(text) as { detail?: unknown };
|
||
} catch {
|
||
if (response.status === 401) notifyUnauthorized();
|
||
throw new ApiError(response.status, `服务出错(${response.status})`);
|
||
}
|
||
}
|
||
if (response.status === 401) notifyUnauthorized();
|
||
if (!response.ok) {
|
||
const detail = data?.detail;
|
||
const message = typeof detail === "string" ? detail : "请求失败";
|
||
throw new ApiError(response.status, message);
|
||
}
|
||
return data as T;
|
||
}
|
||
|
||
export function health() {
|
||
return api<{ ok: boolean }>("/api/health");
|
||
}
|
||
|
||
export async function openLocal(path: string) {
|
||
if (!("__TAURI_INTERNALS__" in window)) return false;
|
||
const { openPath } = await import("@tauri-apps/plugin-opener");
|
||
await openPath(path);
|
||
return true;
|
||
}
|
||
|
||
export async function chooseDirectory() {
|
||
if (!("__TAURI_INTERNALS__" in window)) return null;
|
||
const { open } = await import("@tauri-apps/plugin-dialog");
|
||
const selected = await open({ directory: true, multiple: false });
|
||
return typeof selected === "string" ? selected : null;
|
||
}
|