feat: migrate Payload CMS to MDX and harden static infrastructure

This commit is contained in:
2026-05-04 14:48:04 +02:00
parent d51e220802
commit d3141187ee
165 changed files with 7654 additions and 16136 deletions

View File

@@ -1,5 +1,6 @@
import { getPayload } from 'payload';
import configPromise from '@payload-config';
import fs from 'fs/promises';
import path from 'path';
import matter from 'gray-matter';
import { config } from '@/lib/config';
export function extractExcerpt(content: string): string {
@@ -57,185 +58,59 @@ export function isPostVisible(post: { frontmatter: { date: string; public?: bool
export async function getPostBySlug(slug: string, locale: string): Promise<PostData | null> {
try {
const payload = await getPayload({ config: configPromise });
const filePath = path.join(process.cwd(), 'content', 'posts', `${slug}.mdx`);
const fileContent = await fs.readFile(filePath, 'utf-8');
const { data, content } = matter(fileContent);
// First try: Find in the requested locale
let { docs } = await payload.find({
collection: 'posts',
where: {
slug: { equals: slug },
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
},
locale: locale as any,
draft: config.showDrafts,
limit: 1,
});
// Fallback: If not found, try searching across all locales.
// This happens when a user uses the static language switcher
// e.g. switching from /en/blog/en-slug to /de/blog/en-slug.
if (!docs || docs.length === 0) {
const { docs: crossLocaleDocs } = await payload.find({
collection: 'posts',
where: {
slug: { equals: slug },
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
},
locale: 'all',
draft: config.showDrafts,
limit: 1,
});
if (crossLocaleDocs && crossLocaleDocs.length > 0) {
// Fetch the found document again, but strictly in the requested locale
// so we get the correctly translated fields (like the localized slug)
const { docs: correctLocaleDocs } = await payload.find({
collection: 'posts',
where: {
id: { equals: crossLocaleDocs[0].id },
},
locale: locale as any,
draft: config.showDrafts,
limit: 1,
});
docs = correctLocaleDocs;
let parsedContent = content;
try {
if (content.trim().startsWith('{')) {
parsedContent = JSON.parse(content);
}
} catch (e) {
// Not JSON
}
if (!docs || docs.length === 0) return null;
const doc = docs[0];
return {
slug: doc.slug,
slug,
frontmatter: {
title: doc.title,
date: doc.date,
excerpt: doc.excerpt || '',
category: doc.category || '',
featuredImage:
typeof doc.featuredImage === 'object' && doc.featuredImage !== null
? doc.featuredImage.url || doc.featuredImage.sizes?.card?.url
: null,
focalX:
typeof doc.featuredImage === 'object' && doc.featuredImage !== null
? doc.featuredImage.focalX
: 50,
focalY:
typeof doc.featuredImage === 'object' && doc.featuredImage !== null
? doc.featuredImage.focalY
: 50,
public: doc._status === 'published',
} as PostFrontmatter,
content: doc.content as any, // Native Lexical Editor State
title: data.title || '',
date: data.date || '',
excerpt: data.excerpt || '',
category: data.category || '',
featuredImage: data.featuredImage?.url || data.featuredImage || null,
focalX: data.featuredImage?.focalX || data.focalX || 50,
focalY: data.featuredImage?.focalY || data.focalY || 50,
public: data.public ?? true,
},
content: parsedContent,
};
} catch (error) {
console.error(`[Payload] getPostBySlug failed for ${slug}:`, error);
console.error(`getPostBySlug failed for ${slug}:`, error);
return null;
}
}
export async function getPostSlugs(slug: string, locale: string): Promise<Record<string, string>> {
try {
const payload = await getPayload({ config: configPromise });
// First, find the post in the current locale to get its ID
let { docs } = await payload.find({
collection: 'posts',
where: {
slug: { equals: slug },
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
},
locale: locale as any,
draft: config.showDrafts,
limit: 1,
});
if (!docs || docs.length === 0) {
// Fallback: search across all locales
const { docs: crossLocaleDocs } = await payload.find({
collection: 'posts',
where: {
slug: { equals: slug },
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
},
locale: 'all',
draft: config.showDrafts,
limit: 1,
});
docs = crossLocaleDocs;
}
if (!docs || docs.length === 0) return {};
const postId = docs[0].id;
// Fetch the post with locale 'all' to get all localized fields
const { docs: allLocalesDocs } = await payload.find({
collection: 'posts',
where: {
id: { equals: postId },
},
locale: 'all',
draft: config.showDrafts,
limit: 1,
});
if (!allLocalesDocs || allLocalesDocs.length === 0) return {};
return (allLocalesDocs[0].slug as unknown as Record<string, string>) || {};
} catch (error) {
console.error(`[Payload] getPostSlugs failed for ${slug}:`, error);
return {};
}
// Mock function, simply returns the slug for all locales
return { de: slug, en: slug };
}
export async function getAllPosts(locale: string): Promise<PostData[]> {
try {
const payload = await getPayload({ config: configPromise });
const { docs } = await payload.find({
collection: 'posts',
where: {
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
},
locale: locale as any,
sort: '-date',
draft: config.showDrafts,
limit: 100,
});
const dir = path.join(process.cwd(), 'content', 'posts');
const files = await fs.readdir(dir);
const slugs = files.filter((f) => f.endsWith('.mdx')).map((f) => f.replace('.mdx', ''));
const posts = await Promise.all(slugs.map((slug) => getPostBySlug(slug, locale)));
console.log(`[Payload] getAllPosts for ${locale}: Found ${docs.length} docs`);
const posts = docs.map((doc) => {
return {
slug: doc.slug,
frontmatter: {
title: doc.title,
date: doc.date,
excerpt: doc.excerpt || '',
category: doc.category || '',
featuredImage:
typeof doc.featuredImage === 'object' && doc.featuredImage !== null
? doc.featuredImage.url || doc.featuredImage.sizes?.card?.url
: null,
focalX:
typeof doc.featuredImage === 'object' && doc.featuredImage !== null
? doc.featuredImage.focalX
: 50,
focalY:
typeof doc.featuredImage === 'object' && doc.featuredImage !== null
? doc.featuredImage.focalY
: 50,
} as PostFrontmatter,
// Pass the Lexical content object rather than raw markdown string
content: doc.content as any,
};
});
// Integrity check: only show posts with a featured image in listings/sitemap
return posts.filter((p) => !!p.frontmatter.featuredImage);
const validPosts = posts.filter(
(p): p is PostData => p !== null && !!p.frontmatter.featuredImage,
);
return validPosts.sort(
(a, b) => new Date(b.frontmatter.date).getTime() - new Date(a.frontmatter.date).getTime(),
);
} catch (error) {
console.error(`[Payload] getAllPosts failed for ${locale}:`, error);
console.error(`getAllPosts failed for ${locale}:`, error);
return [];
}
}