60 lines
1.6 KiB
JavaScript
60 lines
1.6 KiB
JavaScript
import { invoke } from "@tauri-apps/api/core";
|
|
|
|
/** API 路径前缀(实际 HTTP 由 Rust `api_request` 发出) */
|
|
const API_BASE = import.meta.env.VITE_API_BASE_URL || "/api/v1";
|
|
|
|
function isTauri() {
|
|
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
|
}
|
|
|
|
/**
|
|
* @param {string} path - 相对 `/api/v1` 的路径,如 `/auth/login`
|
|
* @param {RequestInit} options
|
|
* @returns {Promise<{ ok: boolean, message: string, data?: unknown }>}
|
|
*/
|
|
export async function apiRequest(path, options = {}) {
|
|
if (!isTauri()) {
|
|
return {
|
|
ok: false,
|
|
message: "API 请求需在 Tauri 桌面端运行(由 Rust 代理并加解密)",
|
|
};
|
|
}
|
|
|
|
const method = (options.method || "GET").toUpperCase();
|
|
let body;
|
|
if (options.body != null && options.body !== "") {
|
|
body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
|
|
}
|
|
|
|
const headers = {};
|
|
if (options.headers) {
|
|
const h = options.headers;
|
|
if (h instanceof Headers) {
|
|
h.forEach((value, key) => {
|
|
headers[key] = value;
|
|
});
|
|
} else {
|
|
Object.assign(headers, h);
|
|
}
|
|
}
|
|
|
|
const relPath = path.startsWith("/") ? path : `/${path}`;
|
|
|
|
try {
|
|
const result = await invoke("api_request", {
|
|
path: relPath,
|
|
method,
|
|
body: body ?? null,
|
|
headers: Object.keys(headers).length ? headers : null,
|
|
});
|
|
if (result && typeof result === "object" && "ok" in result) {
|
|
return result;
|
|
}
|
|
return { ok: false, message: "服务器返回格式异常" };
|
|
} catch (err) {
|
|
return { ok: false, message: String(err) };
|
|
}
|
|
}
|
|
|
|
export { API_BASE };
|