先在这里简单的写,保存起来
import responseInterceptor from "./responseInterceptor";
const pendingRequests = new Map();
const resultCache = new Map();
const cacheExpirationTime = 2000;
const cacheCleanupInterval = 60000;
setInterval(cleanUpCache, cacheCleanupInterval);
function cleanUpCache() {
const currentTime = Date.now();
for (const [requestKey, cachedResult] of resultCache.entries()) {
if (currentTime - cachedResult.timestamp >= cacheExpirationTime) {
resultCache.delete(requestKey);
}
}
}
export default async function sendRequest(url, options) {
const requestKey = url + JSON.stringify(options);
const cachedResult = resultCache.get(requestKey);
if (cachedResult) {
const currentTime = Date.now();
if (currentTime - cachedResult.timestamp < cacheExpirationTime) {
return cachedResult.data;
} else {
resultCache.delete(requestKey);
}
}
if (pendingRequests.has(requestKey)) {
return pendingRequests.get(requestKey);
}
const requestPromise = new Promise(async (resolve, reject) => {
try {
const request = await fetch(url, options);
const result = await responseInterceptor(request, { url, init: options });
resolve(result);
resultCache.set(requestKey, { data: result, timestamp: Date.now() });
} catch (error) {
reject(error);
} finally {
pendingRequests.delete(requestKey);
}
});
pendingRequests.set(requestKey, requestPromise);
return requestPromise;
}