GoogleChromeLabs / sw-toolbox

[Deprecated] A collection of service worker tools for offlining runtime requests
https://developers.google.com/web/tools/workbox/guides/migrations/migrate-from-sw
Apache License 2.0
3.61k stars 331 forks source link

Support configuring a custom function with the request object as an input param for URL pattern #262

Closed liuruoran88 closed 7 years ago

liuruoran88 commented 7 years ago

sw-toolbox has two options, Express-style Routes and Regular Expression Routes, for configuring the routes, but it's not flexible enough for users. If it can support configuring a custom function with the request object as an input param for url pattern,users can do more processing according to the request object. In order to meet this need, I have changed two files, lib/router.js and lib/route.js, and added some test cases in the test folder. These changes will not affect the original Routes config.Your prompt attention to this matter will be appreciated.

An example of using Function Expression routing include:

toolbox.router.get(
function(request){
  // users can get request object, do some processing accroding to the request object and return a boolean value
  if (request && reqest.headers && request.headers.referer) {
     return true;
  } 
}, apiHandler);
jeffposnick commented 7 years ago

First off, thanks for your contribution!

While sw-toolbox continues to be a supported project, we're not looking to make significant changes to the public API at this time.

A newer set of libraries, called Workbox, already provides similar functionality to what you're proposing. Specifically, the WorkboxSW.router.registerRoute() method will allow you to pass in a custom function for determining whether there's a match, and then apply a handler similar to what's supported in sw-toolbox.

If you'd prefer to continue using sw-toolbox, what you're proposing is possible without actually changing the public interface if you avoid using the sw-toolbox router, and instead use your own custom routing logic alongside the sw-toolbox strategies, like:

importScripts('/path/to/sw-toolbox.js');

self.addEventListener('fetch', event => {
  if (event.request.headers.has('referer')) {
     event.respondWith(toolbox.networkFirst(event.request));
  }
});