Skip to content

Commit

Permalink
Run user middleware when adding route data to pages
Browse files Browse the repository at this point in the history
  • Loading branch information
delucis committed Dec 23, 2024
1 parent f6f9af5 commit 0107e9a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 9 deletions.
12 changes: 5 additions & 7 deletions packages/starlight/components/StarlightPage.astro
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
import { attachRouteDataAndRunMiddleware } from '../utils/routing/middleware';
import {
generateStarlightPageRouteData,
type StarlightPageProps as Props,
Expand All @@ -7,13 +8,10 @@ import Page from './Page.astro';
export type StarlightPageProps = Props;
// TODO: This is a bit tricky to solve.
// We can’t apply other middleware transformations to route data here, so that makes
// the `<StarlightPage>` behaviour quite different from regular pages.
Astro.locals.starlightRoute = await generateStarlightPageRouteData({
props: Astro.props,
url: Astro.url,
});
await attachRouteDataAndRunMiddleware(
Astro,
await generateStarlightPageRouteData({ props: Astro.props, url: Astro.url })
);
---

<Page><slot /></Page>
5 changes: 3 additions & 2 deletions packages/starlight/locals.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { defineMiddleware } from 'astro:middleware';
import { useTranslations } from './utils/translations';
import { useRouteData } from './utils/routing/data';
import { attachRouteDataAndRunMiddleware } from './utils/routing/middleware';
import { useTranslations } from './utils/translations';

export const onRequest = defineMiddleware(async (context, next) => {
context.locals.t = useTranslations(context.currentLocale);
context.locals.starlightRoute = await useRouteData(context);
await attachRouteDataAndRunMiddleware(context, await useRouteData(context));
return next();
});
19 changes: 19 additions & 0 deletions packages/starlight/utils/routing/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { APIContext } from 'astro';
import { klona } from 'klona/lite';
import { routeMiddleware } from 'virtual:starlight/route-middleware';
import type { StarlightRouteData } from './types';

/**
* Adds a deep clone of the passed `routeData` object to locals and then runs middleware.
* @param context Astro context object
* @param routeData Initial route data object to attach.
*/
export async function attachRouteDataAndRunMiddleware(
context: APIContext,
routeData: StarlightRouteData
) {
context.locals.starlightRoute = klona(routeData);
for (const middlewareFn of routeMiddleware) {
await middlewareFn(context);
}
}

0 comments on commit 0107e9a

Please sign in to comment.