-
Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathssr.ts
184 lines (162 loc) · 4.32 KB
/
ssr.ts
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import fs from "fs/promises";
import App from "./react/App";
import ReactDOMServer from "react-dom/server";
import React from "react";
import API from "./api";
type Method = "GET" | "POST" | "PUT" | "DELETE";
type ResponseOptions = {
contentType?: string;
isBase64Encoded?: boolean;
headers?: Record<string, string>;
statusCode?: number;
};
const ASSET_CACHE: Record<string, string> = {};
const MIME_TYPES = {
js: "text/javascript",
css: "text/css",
html: "text/html",
ico: "image/x-icon",
svg: "image/svg+xml",
png: "image/png",
jpg: "image/jpeg",
};
const htmlFilePromise = fs.readFile("./index.html");
let htmlContent: string | null = null;
class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
const response = (
body: string,
{
contentType = "text/plain",
isBase64Encoded,
headers,
statusCode = 200,
}: ResponseOptions = {}
) => ({
statusCode,
headers: {
"content-type": contentType,
...headers,
},
body,
isBase64Encoded,
});
const apiResponse = async (
pathParams: string[],
method: Method,
body?: string
) => {
const [id] = pathParams;
if (id) {
if (method === "DELETE") {
await API.delete(id);
return response("", {
contentType: "application/json",
});
}
if (method === "PUT") {
const { text, completedDate } = JSON.parse(body);
const item = await API.update({ id, text, completedDate });
return response(JSON.stringify(item), {
contentType: "application/json",
});
}
}
if (pathParams.length == 0 && method === "POST") {
const { text } = JSON.parse(body);
const item = await API.create(text);
return response(JSON.stringify(item), {
contentType: "application/json",
});
}
throw new HttpError(404, "Not found");
};
const appResponse = async () => {
let todoItems;
if (!htmlContent) {
const [html, items] = await Promise.all([htmlFilePromise, API.getAll()]);
htmlContent = html.toString();
todoItems = items;
} else {
todoItems = await API.getAll();
}
const app = ReactDOMServer.renderToString(
React.createElement(App, { todoItems })
);
const html = htmlContent
.replace(
'<script id="init" type="text/javascript"></script>',
`<script id="init" type="text/javascript">
window.todoItems = ${JSON.stringify(todoItems)};
window.releaseName = ${JSON.stringify(process.release.name)}
</script>`
)
.replace('<div id="root"></div>', `<div id="root">${app}</div>`);
return response(html, { contentType: "text/html" });
};
const fileExists = (file: string) =>
fs.access(file).then(
() => true,
() => false
);
const loadAsset = async (asset: string) => {
const safeAsset = asset.replace("..", "");
const cachedAsset = ASSET_CACHE[safeAsset];
if (cachedAsset) {
return cachedAsset;
}
if (!(await fileExists(safeAsset))) {
throw new HttpError(404, "Not found");
}
const data = (await fs.readFile(safeAsset)).toString("base64");
ASSET_CACHE[safeAsset] = data;
return data;
};
const assetResponse = async (path: string) => {
const data = await loadAsset(path);
const extIndex = path.lastIndexOf(".");
let contentType = null;
if (extIndex > -1) {
const ext = path.substring(extIndex + 1);
contentType = MIME_TYPES[ext as keyof typeof MIME_TYPES];
}
return response(data, { contentType, isBase64Encoded: true });
};
export const handler = async (event: any) => {
const { method = "GET", path: eventPath = "/" } =
event?.requestContext?.http || {};
try {
const reqSegments: string[] = (eventPath as string)
.split("/")
.filter((x) => x)
.slice(1);
console.log({ reqSegments, eventPath, method });
if (reqSegments[0] === "api") {
return await apiResponse(reqSegments.slice(1), method, event.body);
}
if (method === "GET") {
if (reqSegments.length === 0) {
return await appResponse();
}
return await assetResponse(reqSegments.join("/"));
}
throw new HttpError(400, "Method not supported");
} catch (e) {
console.error(e);
if (e instanceof HttpError) {
return {
statusCode: e.status,
body: e.message,
};
}
return {
statusCode: 500,
body: "Internal server error",
};
}
};