Skip to content

Commit

Permalink
perf: cache all api responses using a webworker (#882)
Browse files Browse the repository at this point in the history
  • Loading branch information
NoamGaash authored Sep 24, 2024
1 parent fd43a81 commit db0294f
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ module.exports = [
'eslint.config.js',
'.nx',
'jest.config.ts',
'public',
],
},
]
34 changes: 34 additions & 0 deletions public/service-worker.js
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;
});
})
);
}
});
7 changes: 7 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ import 'moment/dist/locale/he'
moment.tz.setDefault('Asia/Jerusalem')
moment.locale('he')

if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js')
.then((reg) => console.log('Service Worker Registered', reg))
.catch((err) => console.error('Service Worker Registration Failed', err))
}

export const RoutedApp = () => (
<Suspense fallback={<Preloader />}>
<RouterProvider router={router} />
Expand Down

0 comments on commit db0294f

Please sign in to comment.