var ConsistentHash = require('consistent-hash');
var hr = new ConsistentHash({distribution: "uniform"});
hr.add('origin_0');
hr.add('origin_1');
hr.add('origin_2');

addEventListener("fetch", event => {
  // Get the request from the client.
  const req = event.request;
  const url = new URL(req.url);
  
  //The hash will use the URL query to generate a hash key
  const resourceName = url.pathname + url.search; 
  const backendToUse = hr.get(resourceName);
  console.log(resourceName + " ---> " + backendToUse);

  // Send the request to the assigned backend.
  const backendResponse = fetch(req, {
    backend: backendToUse
  });

  // Send the backend response back to the client.
  event.respondWith(backendResponse);
});