-
Notifications
You must be signed in to change notification settings - Fork 98
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
perf: cache all api responses using a webworker (#882)
- Loading branch information
Showing
3 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -85,6 +85,7 @@ module.exports = [ | |
'eslint.config.js', | ||
'.nx', | ||
'jest.config.ts', | ||
'public', | ||
], | ||
}, | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
const CACHE_NAME = 'get-requests-cache-v1'; | ||
const CACHE_URLS = []; | ||
|
||
const urlsToFetch = [ | ||
"open-bus-stride-api", | ||
"fonts.googleapis.com" | ||
] | ||
|
||
// Install event: cache basic URLs (optional) | ||
self.addEventListener('install', event => { | ||
event.waitUntil( | ||
caches.open(CACHE_NAME).then(cache => cache.addAll(CACHE_URLS)) | ||
); | ||
}); | ||
|
||
// Fetch event: cache GET requests | ||
self.addEventListener('fetch', event => { | ||
if (event.request.method === 'GET' && urlsToFetch.some(url => event.request.url.includes(url))) { | ||
event.respondWith( | ||
caches.match(event.request).then(cachedResponse => { | ||
// Return cached response if available, else fetch from network | ||
return cachedResponse || fetch(event.request).then(response => { | ||
// Clone the response to save it in the cache | ||
const responseClone = response.clone(); | ||
caches.open(CACHE_NAME).then(cache => { | ||
cache.put(event.request, responseClone); | ||
}); | ||
console.log("cached ", event.request) | ||
return response; | ||
}); | ||
}) | ||
); | ||
} | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters