Skip to content

Instantly share code, notes, and snippets.

@keiraarts
Created December 27, 2020 00:23
Show Gist options
  • Save keiraarts/4efbbbc64aa0bfd87e78de51cb00603f to your computer and use it in GitHub Desktop.
Save keiraarts/4efbbbc64aa0bfd87e78de51cb00603f to your computer and use it in GitHub Desktop.
const HOSTNAME = "iricocanada.com";
const COOKIE_NAME = "__bentocore";
const NAME = "bentocore";
function getCookie(request, name) {
let result = "";
const cookieString = request.headers.get("Cookie");
if (cookieString) {
const cookies = cookieString.split(";");
cookies.forEach((cookie) => {
const cookiePair = cookie.split("=", 2);
const cookieName = cookiePair[0].trim();
if (cookieName === name) {
const cookieVal = cookiePair[1];
result = cookieVal;
}
});
}
return result;
}
async function getProxyUrl(request, income) {
// https://shopify.dev/docs/admin-api/rest/reference/analytics/shopify-ql/sales
const value = await BENTOCORE.get("INCOME#HIGH#URL#demo");
return value;
}
async function TestResponse(request, income) {
// URL is set up to respond with dummy HTML
let proxy = await getProxyUrl(request, income);
request.pathname = proxy;
const url = new URL(request.url);
url.hostname = HOSTNAME;
url.pathname = proxy;
console.log({ proxy: url.toString() });
let response = await fetch(url.toString(), request);
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response);
response.headers.set("x-my-header", "custom value");
return response;
}
async function handleRequest(request) {
const group = Math.random() < 0.5 ? "test" : "control";
let response = await fetch(request, {
cf: {
cacheTtl: 1000,
cacheEverything: true,
},
});
// Reconstruct the Response object to make its headers mutable.
response = new Response(response.body, response);
response.headers.set("x-bentocore", group);
response.headers.set("x-utm_campaign_source", "bentocore");
const CONTROL_RESPONSE = response;
const ip = `192.241.183.25`; // hardcoded for testing
const es = request.headers.get("cf-ipcountry");
console.log({ ip, es });
// Used for GET requests
const init = {
method: "GET",
headers: {
"content-type": "application/json;charset=UTF-8",
},
cf: {
cacheTtl: 1000,
cacheEverything: true,
},
};
// We can't run census data outside of the US
// Cut the worker shortly if that's the case
if (es !== null && es !== "US" && es !== "CA") {
return CONTROL_RESPONSE;
}
// Determine which group this requester is in.
const cookie = request.headers.get("cookie");
// End worker if a cookie exists and we'll server the correct copy of the site
if (cookie && cookie.includes(`${NAME}=control`)) {
// return CONTROL_RESPONSE;
} else if (cookie && cookie.includes(`${NAME}=test`)) {
const incomeGroup = getCookie(request, COOKIE_NAME);
// return await TestResponse(request, incomeGroup);
}
// 1
const ipInfoResponse = await fetch(
`https://ipinfo.io/${ip}?token=` + IPINFO,
init
);
const ipInfo = await ipInfoResponse.json();
console.log({ ipInfo });
// 2
const coordinates = ipInfo.loc.split(",");
const coordinatesRequest = `https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x=${coordinates[1]}&y=${coordinates[0]}&benchmark=4&vintage=4&format=json`;
const geocodeResponse = await fetch(coordinatesRequest, init);
const geocode = await geocodeResponse.json();
console.log({ coordinatesRequest, geocode });
if (geocode && !geocode.result.geographies["2010 Census Blocks"][0]) {
return CONTROL_RESPONSE;
}
// 3
const rawData = geocode.result.geographies["2010 Census Blocks"][0];
const incomeRequest = `https://api.census.gov/data/2018/pdb/blockgroup?get=avg_Agg_HH_INC_ACS_12_16&for=block%20group:1&in=state:${rawData.STATE}%20county:${rawData.COUNTY}%20tract:${rawData.TRACT}&key=` + CENSUSAPI;
const incomeResponse = await fetch(incomeRequest, init);
const income = await incomeResponse.json();
if (income && !income[1][0]) {
return CONTROL_RESPONSE;
}
const earnings = income[1][0];
const modified =
group === "control"
? CONTROL_RESPONSE
: await TestResponse(request, earnings);
modified.headers.append("Set-Cookie", `${NAME}=${group}; path=/`);
modified.headers.append("Set-Cookie", `${COOKIE_NAME}=${earnings}; path=/`);
modified.headers.set("x-bentocore", ip);
return modified;
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment