auth & cache

This commit is contained in:
h z
2024-12-03 11:29:16 +00:00
parent b355b867a5
commit d035a781ae
9 changed files with 118 additions and 9 deletions

View File

@@ -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;
}