auth & cache
This commit is contained in:
@@ -1,4 +1,10 @@
|
||||
const ongoingRequests = new Map();
|
||||
|
||||
export async function fetchWithCache(url, cacheKey = url, cacheExpiry = 60) {
|
||||
if (ongoingRequests.has(url)) {
|
||||
return ongoingRequests.get(url);
|
||||
}
|
||||
|
||||
const cachedData = localStorage.getItem(cacheKey);
|
||||
const now = Date.now();
|
||||
|
||||
@@ -12,13 +18,23 @@ export async function fetchWithCache(url, cacheKey = url, cacheExpiry = 60) {
|
||||
}
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
try {
|
||||
const fetchPromise = fetch(url)
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: now }));
|
||||
ongoingRequests.delete(url);
|
||||
return data;
|
||||
});
|
||||
ongoingRequests.set(url, fetchPromise);
|
||||
return await fetchPromise;
|
||||
} catch (error) {
|
||||
ongoingRequests.delete(url);
|
||||
throw error;
|
||||
}
|
||||
const data = await response.json();
|
||||
|
||||
localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: now }));
|
||||
|
||||
return data;
|
||||
}
|
||||
Reference in New Issue
Block a user