-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
64 lines (51 loc) · 1.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const isUserInternal = request => {
const userId = parseInt(request.headers.get("X-User-Id"));
return userId < 100;
};
const isUserFreeTier = request => {
const userId = parseInt(request.headers.get("X-User-Id"));
return userId >= 100 && userId < 200;
};
const stages = [
{
name: "1",
criteria: isUserInternal
},
{
name: "2",
criteria: isUserFreeTier
}
];
async function getDeployId(request) {
const stateJSON = await RELEASE_STATE.get("state");
const state = JSON.parse(stateJSON);
if (!state.next) {
return state.current;
}
const currentStageIndex = stages.findIndex(
stage => stage.name === state.stage
);
const stagesLeadingUpToCurrentStage = stages.slice(0, currentStageIndex + 1);
if (stagesLeadingUpToCurrentStage.some(stage => stage.criteria(request))) {
return state.next;
}
return state.current;
}
async function handleRequest(request) {
const deployId = await getDeployId(request);
const originalPath = new URL(request.url).pathname.slice(1);
const path = originalPath === "" ? "index.html" : originalPath;
const body = await APP_DEPLOYS.get(`${deployId}/${path}`);
const extensionsToContentTypes = {
css: "text/css",
html: "text/html",
js: "application/javascript"
};
const contentType = extensionsToContentTypes[path.split(".").pop()];
return new Response(body, {
headers: { "Content-Type": contentType }
});
}
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});