~tsileo/blobstash-pwa

284eea2345ffc51f9ba1a1c193d5a9498c783f52 — Thomas Sileo 2 years ago f02c9c1 master
Update th SW
2 files changed, 47 insertions(+), 4 deletions(-)

M app.lua
A templates/service-worker.js
M app.lua => app.lua +8 -4
@@ 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()

A templates/service-worker.js => templates/service-worker.js +39 -0
@@ 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)
      });
    })
  );
});