feat(SW-508): preview for content pages

This commit is contained in:
Erik Tiekstra
2024-10-25 11:28:55 +02:00
parent 18eeeef510
commit bc93fcaefd
8 changed files with 108 additions and 66 deletions

View File

@@ -2,7 +2,6 @@ import { NextResponse } from "next/server"
import { notFound } from "@/server/errors/next"
import { resolve as resolveEntry } from "@/utils/entry"
import { findLang } from "@/utils/languages"
import { removeTrailingSlash } from "@/utils/url"
@@ -18,17 +17,21 @@ export const middleware: NextMiddleware = async (request) => {
const pathWithoutTrailingSlash = removeTrailingSlash(nextUrl.pathname)
const pathNameWithoutLang = pathWithoutTrailingSlash.replace(`/${lang}`, "")
const contentTypePathName = pathWithoutTrailingSlash.replace(`/${lang}`, "")
const isPreview = request.nextUrl.pathname.includes("/preview")
const searchParams = new URLSearchParams(request.nextUrl.searchParams)
const { contentType, uid } = await fetchAndCacheEntry(
pathNameWithoutLang,
isPreview
? contentTypePathName.replace("/preview", "")
: contentTypePathName,
lang
)
if (!contentType || !uid) {
throw notFound(
`Unable to resolve CMS entry for locale "${lang}": ${pathNameWithoutLang}`
`Unable to resolve CMS entry for locale "${lang}": ${contentTypePathName}`
)
}
const headers = getDefaultRequestHeaders(request)
@@ -37,9 +40,9 @@ export const middleware: NextMiddleware = async (request) => {
const isCurrent = contentType ? contentType.indexOf("current") >= 0 : false
if (request.nextUrl.pathname.includes("/preview")) {
if (isPreview) {
if (isCurrent) {
searchParams.set("uri", pathNameWithoutLang.replace("/preview", ""))
searchParams.set("uri", contentTypePathName.replace("/preview", ""))
return NextResponse.rewrite(
new URL(`/${lang}/preview-current?${searchParams.toString()}`, nextUrl),
{
@@ -65,7 +68,7 @@ export const middleware: NextMiddleware = async (request) => {
if (isCurrent) {
searchParams.set("uid", uid)
searchParams.set("uri", pathNameWithoutLang)
searchParams.set("uri", contentTypePathName)
return NextResponse.rewrite(
new URL(
`/${lang}/current-content-page?${searchParams.toString()}`,