2024-11-09 11:30:36 +08:00
|
|
|
import { fetch } from "@tauri-apps/plugin-http";
|
|
|
|
|
|
2025-01-06 10:50:44 +08:00
|
|
|
import { clientEnv } from "@/utils/env";
|
|
|
|
|
|
2024-11-09 11:30:36 +08:00
|
|
|
interface FetchRequestConfig {
|
|
|
|
|
url: string;
|
|
|
|
|
method?: "GET" | "POST" | "PUT" | "DELETE";
|
|
|
|
|
headers?: Record<string, string>;
|
|
|
|
|
body?: any;
|
|
|
|
|
timeout?: number;
|
|
|
|
|
parseAs?: "json" | "text" | "binary";
|
2025-01-09 15:46:34 +08:00
|
|
|
baseURL?: string;
|
2024-11-09 11:30:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface FetchResponse<T = any> {
|
|
|
|
|
data: T;
|
|
|
|
|
status: number;
|
|
|
|
|
statusText: string;
|
|
|
|
|
headers: Headers;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const timeoutPromise = (ms: number) => {
|
|
|
|
|
return new Promise<never>((_, reject) =>
|
|
|
|
|
setTimeout(() => reject(new Error(`Request timed out after ${ms} ms`)), ms)
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const tauriFetch = async <T = any>({
|
|
|
|
|
url,
|
|
|
|
|
method = "GET",
|
|
|
|
|
headers = {},
|
|
|
|
|
body,
|
|
|
|
|
timeout = 30,
|
|
|
|
|
parseAs = "json",
|
2025-01-09 15:46:34 +08:00
|
|
|
baseURL = clientEnv.COCO_SERVER_URL
|
2024-11-09 11:30:36 +08:00
|
|
|
}: FetchRequestConfig): Promise<FetchResponse<T>> => {
|
2025-01-11 10:12:53 +08:00
|
|
|
const { state: { endpoint_http } } = JSON.parse(localStorage.getItem("app-store") || "")
|
|
|
|
|
baseURL = endpoint_http || clientEnv.COCO_SERVER_URL
|
|
|
|
|
console.log("baseURL", baseURL)
|
|
|
|
|
|
|
|
|
|
const { state: { auth } } = JSON.parse(localStorage.getItem("auth-store") || "")
|
|
|
|
|
console.log("auth", auth)
|
2025-01-09 15:46:34 +08:00
|
|
|
|
2024-11-09 11:30:36 +08:00
|
|
|
try {
|
|
|
|
|
url = baseURL + url;
|
|
|
|
|
if (method !== "GET") {
|
|
|
|
|
headers["Content-Type"] = "application/json";
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-11 10:12:53 +08:00
|
|
|
headers["X-API-TOKEN"] = auth?.token || "";
|
2025-01-09 17:41:03 +08:00
|
|
|
|
2024-11-09 11:30:36 +08:00
|
|
|
const fetchPromise = fetch(url, {
|
|
|
|
|
method,
|
|
|
|
|
headers,
|
|
|
|
|
body,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const response = await Promise.race([
|
|
|
|
|
fetchPromise,
|
|
|
|
|
timeoutPromise(timeout * 1000),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
const statusText = response.ok ? "OK" : "Error";
|
|
|
|
|
|
|
|
|
|
let data: any;
|
|
|
|
|
if (parseAs === "json") {
|
|
|
|
|
data = await response.json();
|
|
|
|
|
} else if (parseAs === "text") {
|
|
|
|
|
data = await response.text();
|
|
|
|
|
} else {
|
|
|
|
|
data = await response.arrayBuffer();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
data,
|
|
|
|
|
status: response.status,
|
|
|
|
|
statusText,
|
|
|
|
|
headers: response.headers,
|
|
|
|
|
};
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error("Request failed:", error);
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
};
|