-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlerOriginOverride.js
More file actions
72 lines (62 loc) · 1.78 KB
/
handlerOriginOverride.js
File metadata and controls
72 lines (62 loc) · 1.78 KB
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
65
66
67
68
69
70
71
72
"use strict";
const helpers = require("./helpers/misc");
const http_helpers = require("./helpers/http");
require("source-map-support").install();
module.exports.originOverride = async (event) => {
let request = event.Records[0].cf.request;
let queryString = request.querystring;
// Trim /ch/
let uri = request.uri.substring(4);
// If we have a URI after trimming it means we have been sent a slug that can be used.
let fallbackPath = `/?${queryString}`;
let templateDomain = "wait.crowdhandler.com";
let statusIdentifier = /^status$/;
let templatePath;
if (uri) {
templatePath = `/${uri}`;
} else {
templatePath = fallbackPath;
}
// If the URI is a status page, return the status response.
if (statusIdentifier.test(uri)) {
return http_helpers.statusResponse();
}
// Template fetch with retry mechanic.
let fetchCounter = 0;
async function fetchTemplate(retry) {
let headers = {
"Content-Type": "text/html",
};
let response;
fetchCounter++;
if (fetchCounter === 3) {
templatePath = fallbackPath;
}
try {
response = await http_helpers.httpGET({
headers: headers,
hostname: templateDomain,
method: "GET",
path: templatePath,
port: 443,
});
return response;
} catch (error) {
console.error('Template fetch failed:', error);
response = null;
return response;
}
}
let templateBody;
while (!templateBody && fetchCounter < 4) {
templateBody = await fetchTemplate();
}
if (templateBody) {
let healthyResponse = http_helpers.http200Response(templateBody);
return healthyResponse;
// Handle failure to retrieve template
} else {
let errorResponse = http_helpers.error404Response();
return errorResponse;
}
};