ipfs-shipyard / service-worker-gateway-2019-poc

[ARCHIVED] 2019 PoC of IPFS gateway fully running on a Service Worker. For modern (2024+) version see https://github.com/ipfs-shipyard/service-worker-gateway
MIT License
61 stars 11 forks source link

How to distribute service worker? How will the API be? #7

Open linonetwo opened 6 years ago

linonetwo commented 6 years ago

It's difficult to import script in service worker. There is no window or global in SW, and we can't get an object that exports by an npm package.

I think https://cdn.jsdelivr.net/npm/ipfs/dist/index.js is a good example to follow, it injects a Ipfs object to the context.

Then how will the API be? Are we going to export a function likes getFile and let user write this boilerplate code?

self.addEventListener('install', event => {
  // kick previous sw after install
  console.log('Service worker is installing.');
  event.waitUntil(self.skipWaiting());
});

self.addEventListener('fetch', event => {
  if (event.request.url.startsWith(`${self.location.origin}/${ipfsRoute}`)) {
    const multihashOrContentName = event.request.url.split(`/${ipfsRoute}/`)[1];
    console.log(`Service worker getting ${multihashOrContentName}`);
    event.respondWith(getFile(multihashOrContentName));
  }
});
vasco-santos commented 6 years ago

The first goal here is to allow a website to import this service-worker-gateway package and use it for getting files from an IPFS node running in the service-worker, abstracting everything from the app.

linonetwo commented 6 years ago

@vasco-santos I thought that was the goal of ipfs-service-worker? And service-worker-gateway is letting a website have a route that will load content from IPFS.

linonetwo commented 6 years ago

sw-toolbox let user write two lines of code:

// public/my-service-worker.js
importScripts('bower_components/sw-toolbox/sw-toolbox.js'); // Update path to match your own setup

and

// index.js
navigator.serviceWorker.register('my-service-worker.js');