-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver-common.js
118 lines (98 loc) · 2.64 KB
/
server-common.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
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
/*
This file is shared between the Express/Vite dev server and the Azure Production Function
*/
let fsp = require("fs/promises");
let path = require("path");
var UrlPattern = require("url-pattern");
let redirects = require("./src/redirects");
for (let redirect of redirects) {
redirect.sourcePattern = new UrlPattern(redirect.source);
redirect.destinationPattern = new UrlPattern(redirect.destination);
}
function resolve(p) {
return path.resolve(__dirname, p);
}
function getContentType(ext) {
switch (ext.toLowerCase()) {
case ".css":
return "text/css";
case ".js":
return "text/javascript";
case ".svg":
return "image/svg+xml";
case ".jpg":
case ".jpeg":
return "image/jpg";
case ".png":
return "image/png";
case ".gif":
return "image/gif";
}
return null;
}
module.exports = {
handleRedirect: function (path) {
const redirect = this.getRedirect(path);
if(!redirect) {
return null;
}
return {
status: redirect.permanent ? 301 : 302,
body: "Redirecting to: " + redirect.url,
headers: {
Location: redirect.url,
},
};
},
handleStatic: async function (base, url) {
const file = await fsp.readFile(resolve(base + url.path), "utf8");
const ext = path.extname(url.path);
return {
status: 200,
body: file,
headers: {
"Content-Type": getContentType(ext),
},
};
},
getRedirect: function (url) {
for (let redirect of redirects) {
const match = redirect.sourcePattern.match(url);
if (match) {
return {
url: redirect.destinationPattern.stringify(match),
permanent: redirect.permanent,
};
}
}
return null;
},
handleReact: async function (renderAsync, url, pathToIndexHtml, transformAsync) {
let result = await renderAsync(url);
if(!result.headers["Content-Type"]){
result.headers["Content-Type"] = "text/html";
};
let body = result.body;
const json = JSON.stringify(result.data || {});
if (url.query.__serverside) {
body = json;
result.headers["Content-Type"] = "application/json";
} else if (result.html) {
body = await fsp.readFile(
pathToIndexHtml,
"utf8"
);
if(transformAsync){
body = await transformAsync(body);
}
body = body.replace("<!--app-html-->", result.html);
let data = result.data ? `<script>window.__serverside = ${json};</script>` : "";
body = body.replace("<!--app-data-->", data);
}
return {
status: result.status,
body: body,
headers: result.headers,
};
},
};