77 lines
2.5 KiB
TypeScript
77 lines
2.5 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import matter from 'gray-matter';
|
|
import { remark } from 'remark';
|
|
import gfm from 'remark-gfm';
|
|
import remarkRehype from 'remark-rehype';
|
|
import rehypeRaw from 'rehype-raw';
|
|
import rehypeStringify from 'rehype-stringify';
|
|
|
|
const postsDirectory = path.join(process.cwd(), 'posts');
|
|
|
|
const pinnedPath = path.join(postsDirectory, 'pinned.json');
|
|
let pinnedSlugs: string[] = [];
|
|
if (fs.existsSync(pinnedPath)) {
|
|
try {
|
|
pinnedSlugs = JSON.parse(fs.readFileSync(pinnedPath, 'utf8'));
|
|
} catch {}
|
|
}
|
|
|
|
// Function to get file creation date
|
|
function getFileCreationDate(filePath: string): Date {
|
|
const stats = fs.statSync(filePath);
|
|
return stats.birthtime;
|
|
}
|
|
|
|
async function getPostByPath(filePath: string, relPath: string) {
|
|
const fileContents = fs.readFileSync(filePath, 'utf8');
|
|
const { data, content } = matter(fileContents);
|
|
const createdAt = getFileCreationDate(filePath);
|
|
const processedContent = await remark()
|
|
.use(gfm)
|
|
.use(remarkRehype, { allowDangerousHtml: true })
|
|
.use(rehypeRaw)
|
|
.use(rehypeStringify)
|
|
.process(content);
|
|
return {
|
|
type: 'post',
|
|
slug: relPath.replace(/\.md$/, ''),
|
|
title: data.title,
|
|
date: data.date,
|
|
tags: data.tags || [],
|
|
summary: data.summary,
|
|
content: processedContent.toString(),
|
|
createdAt: createdAt.toISOString(),
|
|
pinned: pinnedSlugs.includes(relPath.replace(/\.md$/, '')),
|
|
};
|
|
}
|
|
|
|
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 tree = await readPostsDir(postsDirectory);
|
|
return NextResponse.json(tree);
|
|
} catch (error) {
|
|
return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
|
|
}
|
|
}
|