Skip to content

Commit

Permalink
Site: Move resolving of redirects from middleware to ...path page (#513)
Browse files Browse the repository at this point in the history
Co-authored-by: Thomas Dax <[email protected]>
  • Loading branch information
nsams and thomasdax98 authored Dec 18, 2024
1 parent 8f2b55e commit 475e2b2
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 213 deletions.
43 changes: 0 additions & 43 deletions site/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"@opentelemetry/auto-instrumentations-node": "^0.53.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.55.0",
"@opentelemetry/sdk-node": "^0.55.0",
"cache-manager": "^5.7.6",
"graphql": "^15.9.0",
"ioredis": "^5.4.1",
"lru-cache": "^11.0.2",
Expand Down
59 changes: 50 additions & 9 deletions site/src/app/[domain]/[language]/[[...path]]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,74 @@
import { gql, previewParams } from "@comet/cms-site";
import { ExternalLinkBlockData, InternalLinkBlockData, RedirectsLinkBlockData } from "@src/blocks.generated";
import { documentTypes } from "@src/documents";
import { GQLPageTreeNodeScopeInput } from "@src/graphql.generated";
import { GQLPageTreeNodeScope } from "@src/graphql.generated";
import { createGraphQLFetch } from "@src/util/graphQLClient";
import { notFound } from "next/navigation";
import { getSiteConfigForDomain } from "@src/util/siteConfig";
import { notFound, redirect } from "next/navigation";

import { GQLDocumentTypeQuery, GQLDocumentTypeQueryVariables } from "./page.generated";

const documentTypeQuery = gql`
query DocumentType($path: String!, $scope: PageTreeNodeScopeInput!) {
pageTreeNodeByPath(path: $path, scope: $scope) {
query DocumentType(
$skipPage: Boolean!
$path: String!
$scope: PageTreeNodeScopeInput!
$redirectSource: String!
$redirectScope: RedirectScopeInput!
) {
pageTreeNodeByPath(path: $path, scope: $scope) @skip(if: $skipPage) {
id
documentType
}
redirectBySource(source: $redirectSource, sourceType: path, scope: $redirectScope) {
target
}
}
`;

export default async function Page({ params: { path, domain, language } }: { params: { path: string[]; domain: string; language: string } }) {
const scope = { domain, language };

export default async function Page({ params }: { params: { path: string[]; domain: string; language: string } }) {
const { previewData } = (await previewParams()) || { previewData: undefined };
const graphqlFetch = createGraphQLFetch(previewData);
const siteConfig = getSiteConfigForDomain(params.domain);

// Redirects are scoped by domain only, not by language.
// If the language param isn't a valid language, it may still be the first segment of a redirect source.
// In that case we skip resolving page and only check if the path is a redirect source.
const skipPage = !siteConfig.scope.languages.includes(params.language);
const path = `/${(params.path ?? []).join("/")}`;
const scope = { domain: params.domain, language: params.language };

//fetch documentType
const data = await graphqlFetch<GQLDocumentTypeQuery, GQLDocumentTypeQueryVariables>(documentTypeQuery, {
path: `/${(path ?? []).join("/")}`,
scope: scope as GQLPageTreeNodeScopeInput, //TODO fix type, the scope from previewParams() is not compatible with GQLPageTreeNodeScopeInput
skipPage,
path,
scope,
redirectSource: `/${params.language}${path !== "/" ? path : ""}`,
redirectScope: { domain: scope.domain },
});

if (!data.pageTreeNodeByPath?.documentType) {
if (data.redirectBySource?.target) {
const target = data.redirectBySource?.target as RedirectsLinkBlockData;
let destination: string | undefined;
if (target.block !== undefined) {
switch (target.block.type) {
case "internal": {
const internalLink = target.block.props as InternalLinkBlockData;
if (internalLink.targetPage) {
destination = `/${(internalLink.targetPage.scope as GQLPageTreeNodeScope).language}/${internalLink.targetPage.path}`;
}
break;
}
case "external":
destination = (target.block.props as ExternalLinkBlockData).targetUrl;
break;
}
}
if (destination) {
redirect(destination);
}
}
notFound();
}

Expand Down
26 changes: 2 additions & 24 deletions site/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { Rewrite } from "next/dist/lib/load-custom-routes";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

import { GQLRedirectScope } from "./graphql.generated";
import { createRedirects } from "./redirects/redirects";
import { configureResponse } from "./util/configureResponse";
import { getHostByHeaders, getSiteConfigForHost, getSiteConfigs } from "./util/siteConfig";

Expand Down Expand Up @@ -31,24 +28,12 @@ export async function middleware(request: NextRequest) {
throw new Error(`Cannot get siteConfig for host ${host}`);
}

const scope = { domain: siteConfig.scope.domain };

if (pathname.startsWith("/dam/")) {
return NextResponse.rewrite(new URL(`${process.env.API_URL_INTERNAL}${request.nextUrl.pathname}`));
}

const redirects = await createRedirects(scope);

const redirect = redirects.get(pathname);
if (redirect) {
const destination: string = redirect.destination;
return NextResponse.redirect(new URL(destination, request.url), redirect.permanent ? 308 : 307);
}

const rewrites = await createRewrites(scope);
const rewrite = rewrites.get(pathname);
if (rewrite) {
return NextResponse.rewrite(new URL(rewrite.destination, request.url));
if (request.nextUrl.pathname === "/admin" && process.env.ADMIN_URL) {
return NextResponse.redirect(new URL(process.env.ADMIN_URL));
}

return configureResponse(
Expand All @@ -64,13 +49,6 @@ export async function middleware(request: NextRequest) {
);
}

type RewritesMap = Map<string, Rewrite>;

async function createRewrites(scope: GQLRedirectScope): Promise<RewritesMap> {
const rewritesMap = new Map<string, Rewrite>();
return rewritesMap;
}

export const config = {
matcher: [
/*
Expand Down
13 changes: 0 additions & 13 deletions site/src/redirects/cache.ts

This file was deleted.

123 changes: 0 additions & 123 deletions site/src/redirects/redirects.ts

This file was deleted.

0 comments on commit 475e2b2

Please sign in to comment.