-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathcreateRoute.js
72 lines (62 loc) · 1.86 KB
/
createRoute.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
import ContextCache from "./ContextCache.js";
import path from "path";
function formatTimeSinceInSeconds(start) {
return Math.ceil((performance.now() - start) / 100) / 10;
}
function serveResult (result, fileName, res, next) {
let bundle, error;
try {
for (const out of result.outputFiles) {
if (path.basename(out.path) === fileName) {
bundle = out.text;
}
}
} catch(e) {
error = e;
}
if (!bundle) {
next(new Error(`Failed to generate bundle: ${fileName}`, {
cause: error
}));
return;
}
res.append("Cache-Control", "max-age=0");
res.append("Content-Type", "application/javascript");
res.send(bundle);
};
function createRoute(app, name, route, context, dependantCaches) {
const cache = new ContextCache(context);
app.get(route, async function (req, res, next) {
const fileName = path.basename(req.originalUrl);
// Multiple files may be requested at this path, calling this function in quick succession.
// Await the previous build before re-building again.
try {
await cache.promise;
} catch {
// Error is reported upstream
}
if (!cache.isBuilt()) {
try {
const start = performance.now();
if (dependantCaches) {
await Promise.all(
dependantCaches.map((dependantCache) => {
if (!dependantCache.isBuilt()) {
return dependantCache.rebuild();
}
})
);
}
await cache.rebuild();
console.log(
`Built ${name} in ${formatTimeSinceInSeconds(start)} seconds.`
);
} catch (e) {
next(e);
}
}
return serveResult(cache.result, fileName, res, next);
});
return cache;
}
export default createRoute;