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

I like this!

I often find when I'm working with changing behavior based on the URL in a Service Worker, it's easier to make an instance of `URL` and look at the parts instead of the original string. It would be nice to have conditions for the pathname, hostname, protocol, query string, etc. as well as other parts of the request. I also agree that there could be an easier way to set the condtions than a constructor.

For example:

```javascript
router.get(
  [
    // same as the RouterIfURLStarts example
    new RouterCondition.url.pathname.startsWith('/avatars/'),
    // true if url.hostname === 'example.com'
    new RouterCondition.url.hostname.is('example.com'),
    // everything should be HTTPS anyway, but since we're here
    new RouterCondition.url.protocol.is('https:'),
    // Skip this route if a queryString is set
    new RouterCondition.url.search.isEmpty(),
    // User has logged in
    new RouterCondition.request.headers.has('X-Authentication-Token'),
    // I'm sure you GET the idea
    new RouterCondition.request.method.is('GET')
  ],
  [
    // ...sources
  ],
)
```

You could also make it so conditions could be easily chained together, similar to how test frameworks do assertions.

```javascript
const profilePictureConditon = RouterCondition.url.pathname
  .startsWith('/users/')
  .endsWith('/profile.jpg');
const profilePageCondition = RouterCondition.url.pathname
  .startsWith('/users/')
  .endsWith('profile.html');
const dateCondition = RouterCondition.date
  .from(someDay)
  .to(anotherDay);
const localizedApiCondition = RouterCondition.url.hostname
  .startsWith('api.')
  .endsWith('.jp')
const globalApiCondition = RouterCondition.url.hostname
  .startsWith('api.')
  .endsWith('.com')
```

This would make code easier to read and I think makes more sense than constructors taxonomically.

All of the `RouterCondition.something.something()`s would return an instance of `RouterCondition`. To play devil's advocate in favor of constructors, I suppose it could have a constructor ...

```javascript
const conditon = new RouterCondition({
  url: {
    hostname: 'example.com',
    pathname: {
      startsWith: '/avatars/'
    },
    protocol: 'https:',
    search: ''
  },
  request: {
    method: 'GET',
    hasHeaders: ['X-Authenticaton-Token']
  }
});
```

... but if somewhere down the line a new condition gets added, I don't know how one would go about checking whether it's supported, so I'd prefer a completely constructor-less API.

-- 
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-452233237

Received on Tuesday, 8 January 2019 09:35:38 UTC