UNPKG

vike

Version:

The Framework *You* Control - Next.js & Nuxt alternative for unprecedented flexibility and dependability.

41 lines (40 loc) 1.8 kB
export { executeGuardHook }; import { getHookFromPageContext, getHookTimeoutDefault } from '../hooks/getHook.js'; import { assert, assertUsage, isCallable } from './utils.js'; import { executeHook } from '../hooks/executeHook.js'; const errIntro = 'The guard() hook defined by'; async function executeGuardHook(pageContext, prepareForUserConsumption) { let hook; if (pageContext._pageFilesAll.length > 0) { // V0.4 design assert(pageContext._pageConfigs.length === 0); hook = findPageGuard(pageContext.pageId, pageContext._pageFilesAll); } else { // V1 design hook = getHookFromPageContext(pageContext, 'guard'); } if (!hook) return; const guard = hook.hookFn; let pageContextForUserConsumption = pageContext; const res = prepareForUserConsumption(pageContext); if (res) pageContextForUserConsumption = res; const hookResult = await executeHook(() => guard(pageContextForUserConsumption), hook, pageContext); assertUsage(hookResult === undefined, `${errIntro} ${hook.hookFilePath} returns a value, but guard() shouldn't return any value`); } 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 }; }