From 4607863b6d26dd0d3728336dcfae1e89dddd6aa7 Mon Sep 17 00:00:00 2001 From: Friedjoff Trautwein Date: Mon, 27 Apr 2020 16:00:35 +0200 Subject: [PATCH] feat: add tiles service worker for offline map --- src/tilesServiceWorker.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/tilesServiceWorker.js diff --git a/src/tilesServiceWorker.js b/src/tilesServiceWorker.js new file mode 100644 index 00000000..aaab8461 --- /dev/null +++ b/src/tilesServiceWorker.js @@ -0,0 +1,26 @@ +const CACHE_NAME = 'tree-app-tiles-v1'; +const { REACT_APP_VECTOR_TILES_ENDPOINT: endpoint } = process.env; + +// eslint-disable-next-line no-restricted-globals +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => { + return fetch(`${endpoint}/tiles.txt`) + .then((response) => response.text()) + .then(async (response) => { + const tiles = response.split(/\r?\n/); + // eslint-disable-next-line no-plusplus + for (let index = 0; index < tiles.length; index++) { + const tileUrl = `${endpoint}/${tiles[index]}`; + try { + // eslint-disable-next-line no-await-in-loop + const tileResponse = await fetch(tileUrl); + cache.put(tileUrl, tileResponse); + } catch (error) { + // Some tiles do not exist. + } + } + }); + }), + ); +});