113 lines
3.1 KiB
JavaScript
113 lines
3.1 KiB
JavaScript
import baseRequest from "./baseRequest";
|
|
import { get } from "./storeInfo";
|
|
import Toast from "react-native-toast-message";
|
|
import { generateSignature } from "./crypto";
|
|
// import { useRouter } from "next/navigation";
|
|
// import webviewBaseRequest from "@/utils/webviewBaseRequest";
|
|
|
|
// 创建一个封装 fetch 的函数
|
|
export default async function customFetch(
|
|
method,
|
|
url,
|
|
options = {},
|
|
needMid,
|
|
timeoutValue = 0
|
|
) {
|
|
const controller = new AbortController();
|
|
const signal = controller.signal;
|
|
|
|
// 设置超时
|
|
|
|
let timeout = null;
|
|
if (timeoutValue) {
|
|
timeout = setTimeout(() => {
|
|
controller.abort("Request timed out");
|
|
}, timeoutValue);
|
|
}
|
|
// 默认选项
|
|
const defaultOptions = {
|
|
method: method,
|
|
signal,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-Req-Source-TF": "wittgenstein",
|
|
...options?.headers,
|
|
// 可以添加其他默认头部信息
|
|
},
|
|
// 可以添加其他默认选项
|
|
};
|
|
let newBody = { ...options?.body };
|
|
if (needMid) {
|
|
let { mid } = await get("account");
|
|
if (!mid) return;
|
|
newBody.mid = mid;
|
|
}
|
|
|
|
const apiUrl = process.env.EXPO_PUBLIC_API_URL;
|
|
const base = await baseRequest();
|
|
const body = JSON.stringify({ ...base, ...newBody });
|
|
|
|
// 合并选项
|
|
const mergedOptions = { ...defaultOptions, body };
|
|
// console.log("body", body);
|
|
// 返回 Promise 对象
|
|
const signature = await generateSignature({
|
|
...base,
|
|
});
|
|
return new Promise((resolve, reject) => {
|
|
try {
|
|
fetch(`${apiUrl + url}?signature=${signature}`, mergedOptions)
|
|
.then((response) => {
|
|
if (timeout) clearTimeout(timeout);
|
|
|
|
// // 检查响应状态码
|
|
if (!response.ok) {
|
|
throw new Error(
|
|
"Network response was not ok " + response.statusText
|
|
);
|
|
}
|
|
// console.log("response-----", response);
|
|
// const contentLength = response.headers.get("Content-Length");
|
|
// if (!contentLength) {
|
|
// throw new Error("Content-Length is null");
|
|
// }
|
|
|
|
// const total = parseInt(contentLength, 10);
|
|
// let loaded = 0;
|
|
// alert("Error--" + url + "-----" + response);
|
|
return response;
|
|
// 解析 JSON 响应
|
|
// return response.json();
|
|
})
|
|
.then((data) => {
|
|
// 解析成功,返回数据
|
|
resolve(data.json());
|
|
})
|
|
.catch((error) => {
|
|
// alert("ErrorCatch" + error);
|
|
if (error.name === "AbortError") {
|
|
// console.log("Fetch request timed out.");
|
|
Toast.show({
|
|
type: "error",
|
|
text1: "请求超时,请检查网络后重试。",
|
|
topOffset: 60,
|
|
});
|
|
// 这里可以实现重试逻辑
|
|
// fetchDataWithRetry();
|
|
} else {
|
|
console.error("Fetch error:", error);
|
|
}
|
|
|
|
// 请求失败,拒绝 Promise
|
|
reject(error);
|
|
});
|
|
} catch (error) {
|
|
Toast.show({
|
|
type: "error",
|
|
text1: "请求数据出现问题!",
|
|
topOffset: 60,
|
|
});
|
|
}
|
|
});
|
|
}
|