Skip to content

Commit

Permalink
refactor(@angular/ssr): add option to exclude fallback SSG routes fro…
Browse files Browse the repository at this point in the history
…m extraction

This option allows validation during the build process to ensure that, when the output mode is set to static, no routes requiring server-side rendering are included.
  • Loading branch information
alan-agius4 committed Sep 17, 2024
1 parent f346ee8 commit ea4b99b
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 17 deletions.
50 changes: 33 additions & 17 deletions packages/angular/ssr/src/routes/ng-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,25 @@ interface AngularRouterConfigResult {
* @param options - The configuration options for traversing routes.
* @returns An async iterable iterator yielding either route tree node metadata or an error object with an error message.
*/
async function* traverseRoutesConfig({
routes,
compiler,
parentInjector,
parentRoute,
serverConfigRouteTree,
invokeGetPrerenderParams,
}: {
async function* traverseRoutesConfig(options: {
routes: Route[];
compiler: Compiler;
parentInjector: Injector;
parentRoute: string;
serverConfigRouteTree: RouteTree<ServerConfigRouteTreeAdditionalMetadata> | undefined;
invokeGetPrerenderParams: boolean;
includePrerenderFallbackRoutes: boolean;
}): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {
const {
routes,
compiler,
parentInjector,
parentRoute,
serverConfigRouteTree,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
} = options;

for (const route of routes) {
try {
const { path = '', redirectTo, loadChildren, children } = route;
Expand Down Expand Up @@ -147,20 +151,22 @@ async function* traverseRoutesConfig({
yield { ...metadata, redirectTo: redirectToResolved };
} else if (metadata.renderMode === RenderMode.Prerender) {
// Handle SSG routes
yield* handleSSGRoute(metadata, parentInjector, invokeGetPrerenderParams);
yield* handleSSGRoute(
metadata,
parentInjector,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
);
} else {
yield metadata;
}

// Recursively process child routes
if (children?.length) {
yield* traverseRoutesConfig({
...options,
routes: children,
compiler,
parentInjector,
parentRoute: currentRoutePath,
serverConfigRouteTree,
invokeGetPrerenderParams,
});
}

Expand All @@ -175,12 +181,10 @@ async function* traverseRoutesConfig({
if (loadedChildRoutes) {
const { routes: childRoutes, injector = parentInjector } = loadedChildRoutes;
yield* traverseRoutesConfig({
...options,
routes: childRoutes,
compiler,
parentInjector: injector,
parentRoute: currentRoutePath,
serverConfigRouteTree,
invokeGetPrerenderParams,
});
}
}
Expand All @@ -197,12 +201,14 @@ async function* traverseRoutesConfig({
* @param metadata - The metadata associated with the route tree node.
* @param parentInjector - The dependency injection container for the parent route.
* @param invokeGetPrerenderParams - A flag indicating whether to invoke the `getPrerenderParams` function.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result.
* @returns An async iterable iterator that yields route tree node metadata for each SSG path or errors.
*/
async function* handleSSGRoute(
metadata: ServerConfigRouteTreeNodeMetadata,
parentInjector: Injector,
invokeGetPrerenderParams: boolean,
includePrerenderFallbackRoutes: boolean,
): AsyncIterableIterator<RouteTreeNodeMetadata | { error: string }> {
if (metadata.renderMode !== RenderMode.Prerender) {
throw new Error(
Expand Down Expand Up @@ -267,7 +273,10 @@ async function* handleSSGRoute(
}

// Handle fallback render modes
if (fallback !== PrerenderFallback.None || !invokeGetPrerenderParams) {
if (
includePrerenderFallbackRoutes &&
(fallback !== PrerenderFallback.None || !invokeGetPrerenderParams)
) {
yield {
...meta,
route: currentRoutePath,
Expand Down Expand Up @@ -345,13 +354,16 @@ function buildServerConfigRouteTree(serverRoutesConfig: ServerRoute[]): {
* for ensuring that API requests for relative paths succeed, which is essential for accurate route extraction.
* @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes
* to handle prerendering paths. Defaults to `false`.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.
*
* @returns A promise that resolves to an object of type `AngularRouterConfigResult` or errors.
*/
export async function getRoutesFromAngularRouterConfig(
bootstrap: AngularBootstrap,
document: string,
url: URL,
invokeGetPrerenderParams = false,
includePrerenderFallbackRoutes = true,
): Promise<AngularRouterConfigResult> {
const { protocol, host } = url;

Expand Down Expand Up @@ -418,6 +430,7 @@ export async function getRoutesFromAngularRouterConfig(
parentRoute: '',
serverConfigRouteTree,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
});

for await (const result of traverseRoutes) {
Expand Down Expand Up @@ -454,6 +467,7 @@ export async function getRoutesFromAngularRouterConfig(
* If not provided, the default manifest is retrieved using `getAngularAppManifest()`.
* @param invokeGetPrerenderParams - A boolean flag indicating whether to invoke `getPrerenderParams` for parameterized SSG routes
* to handle prerendering paths. Defaults to `false`.
* @param includePrerenderFallbackRoutes - A flag indicating whether to include fallback routes in the result. Defaults to `true`.
*
* @returns A promise that resolves to an object containing:
* - `routeTree`: A populated `RouteTree` containing all extracted routes from the Angular application.
Expand All @@ -463,6 +477,7 @@ export async function extractRoutesAndCreateRouteTree(
url: URL,
manifest: AngularAppManifest = getAngularAppManifest(),
invokeGetPrerenderParams = false,
includePrerenderFallbackRoutes = true,
): Promise<{ routeTree: RouteTree; errors: string[] }> {
const routeTree = new RouteTree();
const document = await new ServerAssets(manifest).getIndexServerHtml();
Expand All @@ -472,6 +487,7 @@ export async function extractRoutesAndCreateRouteTree(
document,
url,
invokeGetPrerenderParams,
includePrerenderFallbackRoutes,
);

for (const { route, ...metadata } of routes) {
Expand Down
81 changes: 81 additions & 0 deletions packages/angular/ssr/test/routes/ng-routes_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,85 @@ describe('extractRoutesAndCreateRouteTree', () => {
{ route: '/user/:id/role/:role', renderMode: RenderMode.Server },
]);
});

it('should not include fallback routes for SSG when `includePrerenderFallbackRoutes` is false', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
fallback: PrerenderFallback.Client,
renderMode: RenderMode.Prerender,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);

const { routeTree, errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ true,
/** includePrerenderFallbackRoutes */ false,
);

expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
]);
});

it('should include fallback routes for SSG when `includePrerenderFallbackRoutes` is true', async () => {
setAngularAppTestingManifest(
[
{ path: 'home', component: DummyComponent },
{ path: 'user/:id/role/:role', component: DummyComponent },
],
[
{
path: 'user/:id/role/:role',
renderMode: RenderMode.Prerender,
fallback: PrerenderFallback.Client,
async getPrerenderParams() {
return [
{ id: 'joe', role: 'admin' },
{ id: 'jane', role: 'writer' },
];
},
},
{ path: '**', renderMode: RenderMode.Server },
],
);

const { routeTree, errors } = await extractRoutesAndCreateRouteTree(
url,
/** manifest */ undefined,
/** invokeGetPrerenderParams */ true,
/** includePrerenderFallbackRoutes */ true,
);

expect(errors).toHaveSize(0);
expect(routeTree.toObject()).toEqual([
{ route: '/home', renderMode: RenderMode.Server },
{ route: '/user/joe/role/admin', renderMode: RenderMode.Prerender },
{
route: '/user/jane/role/writer',
renderMode: RenderMode.Prerender,
},
{ route: '/user/:id/role/:role', renderMode: RenderMode.Client },
]);
});
});

0 comments on commit ea4b99b

Please sign in to comment.