Re: [w3c/ServiceWorker] Declarative routing (#1373)

@jakearchibald 
> > I feel like not adding an additional Source type that utilises a callback is a missed opportunity
> 
> I explored that idea, but here's the issue, (spooky music) the callback ceases to exist. It only ever exists when the install event callback is called. Then later, the service worker closes, the callback is gone. Even later, when the service worker is started again, the install event callback isn't called again, so the callback still doesn't exist (and even if we called that callback again, the callback would be a different instance).

Ah I totally get you, mmm there's no good workaround for that really. Which is a shame. I can imagine the condition matching behaviour being duplicated in a user land library, just to provide a callback style source. I actually already have a project which could benefit from that.

> > I think syntax wise I feel it reads better to have static methods on a RouterCondition/RouterSource class that instantiate the specific type
> 
> I explored this too. What does RouterCondition.startsWith("/avatars/") return? Does that type have a constructor? That's how I landed at constructors.

I was thinking it would either return a new instance of RouterCondition, with a `{ startsWith: "/avatars/" }` configuration or an instance of RouterIfURLStarts ( which would inherit/implement RouterCondition ). RouterCondition itself would be exposed on serviceworkerglobalscope but as an illegal constructor.

If I was to polyfill the feature in JS:

```javascript
class RouterCondition {

    constructor (fn) {
        this._test = fn;
    }

    _check (fetchEvent) {
        return !!this._test(fetchEvent);
    }

    static startsWith(str) {
        return new RouterCondition(fetchEvent => {
            const url = new URL(e.request.url);
            return url.pathname.startsWith(str);
        });
    }
    
}
```

Reading feedback from @domenic  I agree that it does feel somewhat over the top to have a dozen userland classes for what is effectively immutable configuration information. Can anyone think of any methods that Conditions or Sources would actually need? The [type object pattern](http://gameprogrammingpatterns.com/type-object.html) would probably work here.

The static method suggestion I'm putting forward helps with feature detection, and stops developers needing to go **Full Java**. But I admit your latest suggestion reads very cleanly.

```javascript
router.add(
  { url: { matches: '/', ignoreSearch: true } },
  new RouterSourceCache('/shell.html'),
);
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1373#issuecomment-452279034

Received on Tuesday, 8 January 2019 12:20:20 UTC