cesium/scripts/createRoute.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

75 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2023-09-15 03:56:25 +08:00
import ContextCache from "./ContextCache.js";
import path from "path";
function formatTimeSinceInSeconds(start) {
2025-04-26 02:17:23 +08:00
return Math.ceil((performance.now() - start) / 100) / 10;
2023-09-15 03:56:25 +08:00
}
2025-04-26 02:17:23 +08:00
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;
2023-09-15 03:56:25 +08:00
}
}
2025-04-26 02:17:23 +08:00
} 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);
}
2023-09-15 03:56:25 +08:00
function createRoute(app, name, route, context, dependantCaches) {
2025-04-26 02:17:23 +08:00
const cache = new ContextCache(context);
app.get(route, async function (req, res, next) {
const fileName = path.basename(req.originalUrl);
2025-04-26 02:17:23 +08:00
// 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 {
2025-04-26 02:17:23 +08:00
const start = performance.now();
if (dependantCaches) {
await Promise.all(
dependantCaches.map((dependantCache) => {
if (!dependantCache.isBuilt()) {
return dependantCache.rebuild();
}
}),
2023-09-15 03:56:25 +08:00
);
}
2025-04-26 02:17:23 +08:00
await cache.rebuild();
console.log(
`Built ${name} in ${formatTimeSinceInSeconds(start)} seconds.`,
);
} catch (e) {
next(e);
2023-09-15 03:56:25 +08:00
}
2025-04-26 02:17:23 +08:00
}
return serveResult(cache.result, fileName, res, next);
});
return cache;
}
2023-09-15 03:56:25 +08:00
2025-04-26 02:17:23 +08:00
export default createRoute;