folder support

This commit is contained in:
rattatwinko
2025-06-16 17:11:26 +02:00
parent 439d673e8f
commit 92fb64733b
5 changed files with 119 additions and 46 deletions

View File

@@ -13,19 +13,14 @@ function getFileCreationDate(filePath: string): Date {
return stats.birthtime;
}
async function getPostBySlug(slug: string) {
const realSlug = slug.replace(/\.md$/, '');
const fullPath = path.join(postsDirectory, `${realSlug}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
async function getPostByPath(filePath: string, relPath: string) {
const fileContents = fs.readFileSync(filePath, 'utf8');
const { data, content } = matter(fileContents);
const createdAt = getFileCreationDate(fullPath);
const processedContent = await remark()
.use(html)
.process(content);
const createdAt = getFileCreationDate(filePath);
const processedContent = await remark().use(html).process(content);
return {
slug: realSlug,
type: 'post',
slug: relPath.replace(/\.md$/, ''),
title: data.title,
date: data.date,
tags: data.tags || [],
@@ -35,27 +30,31 @@ async function getPostBySlug(slug: string) {
};
}
async function getAllPosts() {
const fileNames = fs.readdirSync(postsDirectory);
const allPostsData = await Promise.all(
fileNames
.filter((fileName) => fileName.endsWith('.md'))
.map(async (fileName) => {
const slug = fileName.replace(/\.md$/, '');
return getPostBySlug(slug);
})
);
return allPostsData.sort((a, b) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
);
async function readPostsDir(dir: string, relDir = ''): Promise<any[]> {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const folders: any[] = [];
const posts: any[] = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relPath = relDir ? path.join(relDir, entry.name) : entry.name;
if (entry.isDirectory()) {
const children = await readPostsDir(fullPath, relPath);
folders.push({ type: 'folder', name: entry.name, path: relPath, children });
} else if (entry.isFile() && entry.name.endsWith('.md')) {
posts.push(await getPostByPath(fullPath, relPath));
}
}
// Sort posts by creation date (newest first)
posts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
// Folders first, then posts
return [...folders, ...posts];
}
export async function GET() {
try {
const posts = await getAllPosts();
return NextResponse.json(posts);
const tree = await readPostsDir(postsDirectory);
return NextResponse.json(tree);
} catch (error) {
return NextResponse.json({ error: 'Failed to fetch posts' }, { status: 500 });
return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
}
}