Skip to content

Commit

Permalink
Break up cache.fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
steinbro committed Nov 28, 2024
1 parent 2e24b2a commit 2cdae4e
Showing 1 changed file with 33 additions and 36 deletions.
69 changes: 33 additions & 36 deletions src/state/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,52 +121,49 @@ export const cache = {
lastFetchTime === null ||
currentTime - lastFetchTime > maxAgeMilliseconds
);
//TODO cache.deleteFeatures(tileKey);
},

// Function to fetch a URL only if it hasn't been fetched for a certain duration
fetch: function(url: string, tileKey: string): Promise<any> {
updateLastFetch: function(url: string): Promise<boolean> {
return new Promise(async (resolve, reject) => {
if (!await cache.shouldFetch(url)) {
resolve(null);
return;
}

if (!cache.db) {
cache.db = await openDatabase();
}

// Fetch the URL since it's not in the cache or has expired
try {
const response = await fetch(url);
const data = await response.json();

const newTransaction = cache.db.transaction(['urls'], 'readwrite');
const newObjectStore = newTransaction.objectStore('urls');

// Update or add the URL in the cache with the current timestamp
const putRequest = newObjectStore.put({
url: url,
lastFetchTime: new Date().getTime(),
// No need to keep the data (the individual features should be
// loaded into their own object store on first fetch)
//cachedData: data,
});

putRequest.onsuccess = () => {
console.log("Fetched: ", url);
resolve(data);
};

putRequest.onerror = (event: Event) => {
reject(`Error updating cache: ${(event.target as IDBEventTargetWithResult).error}`);
};
} catch (error) {
reject(`Error fetching URL: ${error}`);
}
const newTransaction = cache.db.transaction(['urls'], 'readwrite');
const newObjectStore = newTransaction.objectStore('urls');

// Update or add the URL in the cache with the current timestamp
const putRequest = newObjectStore.put({
url: url,
lastFetchTime: new Date().getTime(),
});

putRequest.onsuccess = () => {
console.log("Fetched: ", url);
resolve(true);
};

putRequest.onerror = (event: Event) => {
reject(`Error updating cache: ${(event.target as IDBEventTargetWithResult).error}`);
};
});
},

// Function to fetch a URL only if it hasn't been fetched for a certain duration
fetch: async function(url: string, tileKey: string): Promise<any> {
if (!await cache.shouldFetch(url)) {
return null;
}

// Delete any stale features
cache.deleteFeatures(tileKey);

// Fetch the URL since it's not in the cache or has expired
const response = await fetch(url);
cache.updateLastFetch(url);
return await response.json();
},

// Function to add GeoJSON feature to the cache
addFeature: function(feature: SoundscapeFeature, tile: string): Promise<void> {
return new Promise(async (resolve, reject) => {
Expand Down

0 comments on commit 2cdae4e

Please sign in to comment.