78 lines
2.4 KiB
Plaintext
78 lines
2.4 KiB
Plaintext
import { stringifyParams } from "../routing/params.js";
|
|
import { validateDynamicRouteModule, validateGetStaticPathsResult } from "../routing/validation.js";
|
|
import { generatePaginateFunction } from "./paginate.js";
|
|
async function callGetStaticPaths({
|
|
mod,
|
|
route,
|
|
routeCache,
|
|
logger,
|
|
ssr
|
|
}) {
|
|
const cached = routeCache.get(route);
|
|
if (!mod) {
|
|
throw new Error("This is an error caused by Astro and not your code. Please file an issue.");
|
|
}
|
|
if (cached?.staticPaths) {
|
|
return cached.staticPaths;
|
|
}
|
|
validateDynamicRouteModule(mod, { ssr, route });
|
|
if (ssr && !route.prerender) {
|
|
const entry = Object.assign([], { keyed: /* @__PURE__ */ new Map() });
|
|
routeCache.set(route, { ...cached, staticPaths: entry });
|
|
return entry;
|
|
}
|
|
let staticPaths = [];
|
|
if (!mod.getStaticPaths) {
|
|
throw new Error("Unexpected Error.");
|
|
}
|
|
staticPaths = await mod.getStaticPaths({
|
|
// Q: Why the cast?
|
|
// A: So users downstream can have nicer typings, we have to make some sacrifice in our internal typings, which necessitate a cast here
|
|
paginate: generatePaginateFunction(route)
|
|
});
|
|
validateGetStaticPathsResult(staticPaths, logger, route);
|
|
const keyedStaticPaths = staticPaths;
|
|
keyedStaticPaths.keyed = /* @__PURE__ */ new Map();
|
|
for (const sp of keyedStaticPaths) {
|
|
const paramsKey = stringifyParams(sp.params, route);
|
|
keyedStaticPaths.keyed.set(paramsKey, sp);
|
|
}
|
|
routeCache.set(route, { ...cached, staticPaths: keyedStaticPaths });
|
|
return keyedStaticPaths;
|
|
}
|
|
class RouteCache {
|
|
logger;
|
|
cache = {};
|
|
mode;
|
|
constructor(logger, mode = "production") {
|
|
this.logger = logger;
|
|
this.mode = mode;
|
|
}
|
|
/** Clear the cache. */
|
|
clearAll() {
|
|
this.cache = {};
|
|
}
|
|
set(route, entry) {
|
|
if (this.mode === "production" && this.cache[route.component]?.staticPaths) {
|
|
this.logger.warn(null, `Internal Warning: route cache overwritten. (${route.component})`);
|
|
}
|
|
this.cache[route.component] = entry;
|
|
}
|
|
get(route) {
|
|
return this.cache[route.component];
|
|
}
|
|
}
|
|
function findPathItemByKey(staticPaths, params, route, logger) {
|
|
const paramsKey = stringifyParams(params, route);
|
|
const matchedStaticPath = staticPaths.keyed.get(paramsKey);
|
|
if (matchedStaticPath) {
|
|
return matchedStaticPath;
|
|
}
|
|
logger.debug("router", `findPathItemByKey() - Unexpected cache miss looking for ${paramsKey}`);
|
|
}
|
|
export {
|
|
RouteCache,
|
|
callGetStaticPaths,
|
|
findPathItemByKey
|
|
};
|