-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
123 lines (103 loc) · 2.96 KB
/
index.js
File metadata and controls
123 lines (103 loc) · 2.96 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"use strict";
const http = require("https");
const indexPage = "index.html";
exports.handler = async (event, context, callback) => {
const cf = event.Records[0].cf;
const request = cf.request;
const response = cf.response;
const statusCode = response.status;
// Only replace 403 and 404 requests typically received
// when loading a page for a SPA that uses client-side routing
const doReplace =
request.method === "GET" && (statusCode == "403" || statusCode == "404");
const result = doReplace
? await generateResponseAndLog(cf, request, indexPage)
: response;
if (response.headers["via"]) {
result.headers["via"] = response.headers["via"];
}
if (response.headers["transfer-encoding"]) {
result.headers["transfer-encoding"] = response.headers["transfer-encoding"];
}
callback(null, result);
};
async function generateResponseAndLog(cf, request, indexPage) {
const domain = cf.config.distributionDomainName;
const indexPath = `/${indexPage}`;
const response = await generateResponse(domain, indexPath);
return response;
}
async function generateResponse(domain, path) {
try {
// Load HTML index from the CloudFront cache
const s3Response = await httpGet({ hostname: domain, path: path });
const headers = s3Response.headers;
return {
status: "200",
headers: wrapAndFilterHeaders(headers),
body: s3Response.body,
};
} catch (error) {
return {
status: "500",
headers: {
"content-type": [{ value: "text/plain" }],
},
body: "An error occurred loading the page",
};
}
}
function httpGet(params) {
return new Promise((resolve, reject) => {
http
.get(params, (resp) => {
console.log(
`Fetching ${params.hostname}${params.path}, status code : ${resp.statusCode}`
);
let result = {
headers: resp.headers,
body: "",
};
resp.on("data", (chunk) => {
result.body += chunk;
});
resp.on("end", () => {
resolve(result);
});
})
.on("error", (err) => {
console.log(
`Couldn't fetch ${params.hostname}${params.path} : ${err.message}`
);
reject(err, null);
});
});
}
// Cloudfront requires header values to be wrapped in an array
function wrapAndFilterHeaders(headers) {
const allowedHeaders = [
"content-type",
"content-length",
"last-modified",
"date",
"etag",
];
const responseHeaders = {};
if (!headers) {
return responseHeaders;
}
for (var propName in headers) {
// only include allowed headers
if (allowedHeaders.includes(propName.toLowerCase())) {
var header = headers[propName];
if (Array.isArray(header)) {
// assume already 'wrapped' format
responseHeaders[propName] = header;
} else {
// fix to required format
responseHeaders[propName] = [{ value: header }];
}
}
}
return responseHeaders;
}