From 284eea2345ffc51f9ba1a1c193d5a9498c783f52 Mon Sep 17 00:00:00 2001 From: Thomas Sileo Date: Thu, 30 Jan 2020 23:54:57 +0100 Subject: [PATCH] Update th SW --- app.lua | 12 ++++++++---- templates/service-worker.js | 39 +++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 templates/service-worker.js diff --git a/app.lua b/app.lua index b1cc959..6f31a7d 100644 --- a/app.lua +++ b/app.lua @@ -67,9 +67,13 @@ router:post("/share-target", function(params) app.response:redirect("/api/apps/" .. blobstash.app_id .. "/") end) -router:get("/service-worker.js", function(params) - app.response:headers():set("Content-Type", "application/javascript") - app.response:write('self.addEventListener("fetch", function (event) { event.respondWith(fetch(event.request)); });') -end) +function register_js(name) + router:get("/" .. name, function(params) + app.response:headers():set("Content-Type", "application/javascript") + app.response:write(template.render(name, {app_id = blobstash.app_id})) + end) +end + +register_js("service-worker.js") router:run() diff --git a/templates/service-worker.js b/templates/service-worker.js new file mode 100644 index 0000000..67af343 --- /dev/null +++ b/templates/service-worker.js @@ -0,0 +1,39 @@ +const cacheName = 'v1' + +self.addEventListener('install', function(event) { + event.waitUntil( + caches.open(cacheName).then(function(cache) { + return cache.addAll([ + '/api/apps/{{.app_id}}/', + '/api/apps/{{.app_id}}/service-worker.js', + ]); + }) + ); +}); + +self.addEventListener('activate', function(event) { + event.waitUntil( + caches.keys().then(function(cacheNames) { + return Promise.all( + cacheNames.filter(function(name) { + return name != cacheName; + }).map(function(name) { + return caches.delete(name); + }) + ); + }) + ); +}); + +self.addEventListener('fetch', function(event) { + event.respondWith( + caches.open(cacheName).then(function(cache) { + var fetchPromise = fetch(event.request).then(function(networkResponse) { + cache.put(event.request, networkResponse.clone()); + return networkResponse; + }).catch(() => { + return cache.match(event.request) + }); + }) + ); +}); -- 2.45.2