var ConsistentHash = require('consistent-hash');
var hr = new ConsistentHash({distribution: "uniform"})
hr.add('origin_0');
hr.add('origin_1');
const parseCookie = str =>
str
.split(';')
.map(v => v.split('='))
.reduce((acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
return acc;
}, {});
addEventListener("fetch", event => {
const req = event.request;
const cookies = parseCookie(req.headers.get("cookie"));
const resourceName = cookies["user-id"];
const backendToUse = hr.get(resourceName);
console.log(resourceName + " --> " + backendToUse);
const backendResponse = fetch(req, {
backend: backendToUse
});
event.respondWith(backendResponse);
});