vike
Version:
The Framework *You* Control - Next.js & Nuxt alternative for unprecedented flexibility and dependability.
36 lines (35 loc) • 1.51 kB
JavaScript
export { execHookGuard };
import { getHookFromPageContext, getHookTimeoutDefault } from '../hooks/getHook.js';
import { assert, assertUsage, isCallable } from './utils.js';
import { execHookDirectSingle } from '../hooks/execHook.js';
const errIntro = 'The guard() hook defined by';
async function execHookGuard(pageContext, prepareForPublicUsage) {
let hook;
if (pageContext._globalContext._pageFilesAll.length > 0) {
// TODO/v1-release: remove
// V0.4 design
assert(pageContext._globalContext._pageConfigs.length === 0);
hook = findPageGuard(pageContext.pageId, pageContext._globalContext._pageFilesAll);
}
else {
// V1 design
hook = getHookFromPageContext(pageContext, 'guard');
}
if (!hook)
return;
await execHookDirectSingle(hook, pageContext, prepareForPublicUsage);
}
function findPageGuard(pageId, pageFilesAll) {
const pageRouteFile = pageFilesAll.find((p) => p.pageId === pageId && p.fileType === '.page.route');
if (!pageRouteFile)
return null;
const { filePath, fileExports } = pageRouteFile;
assert(fileExports); // loadPageRoutes() should already have been called
const hookFn = fileExports.guard;
if (!hookFn)
return null;
const hookFilePath = filePath;
const hookTimeout = getHookTimeoutDefault('guard');
assertUsage(isCallable(hookFn), `${errIntro} ${hookFilePath} should be a function`);
return { hookFn, hookName: 'guard', hookFilePath, hookTimeout };
}