113 lines
3.5 KiB
TypeScript
113 lines
3.5 KiB
TypeScript
export const dynamic = "force-dynamic";
|
|
|
|
import { NextResponse } from 'next/server';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import matter from 'gray-matter';
|
|
import { marked } from 'marked';
|
|
import DOMPurify from 'dompurify';
|
|
import { JSDOM } from 'jsdom';
|
|
|
|
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 {
|
|
pinnedSlugs = [];
|
|
}
|
|
}
|
|
|
|
// Function to get file creation date
|
|
function getFileCreationDate(filePath: string): Date {
|
|
const stats = fs.statSync(filePath);
|
|
return stats.birthtime ?? stats.mtime;
|
|
}
|
|
|
|
async function getPostByPath(filePath: string, relPath: string) {
|
|
const fileContents = fs.readFileSync(filePath, 'utf8');
|
|
const { data, content } = matter(fileContents);
|
|
const createdAt = getFileCreationDate(filePath);
|
|
|
|
let processedContent = '';
|
|
try {
|
|
marked.setOptions({
|
|
gfm: true,
|
|
breaks: true
|
|
});
|
|
const rawHtml = marked.parse(content);
|
|
const window = new JSDOM('').window;
|
|
const purify = DOMPurify(window);
|
|
processedContent = purify.sanitize(rawHtml as string, {
|
|
ALLOWED_TAGS: [
|
|
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
|
'p', 'a', 'ul', 'ol', 'li', 'blockquote',
|
|
'pre', 'code', 'em', 'strong', 'del',
|
|
'hr', 'br', 'img', 'table', 'thead', 'tbody',
|
|
'tr', 'th', 'td', 'div', 'span', 'iframe'
|
|
],
|
|
ALLOWED_ATTR: [
|
|
'class', 'id', 'style',
|
|
'href', 'target', 'rel',
|
|
'src', 'alt', 'title', 'width', 'height',
|
|
'frameborder', 'allowfullscreen'
|
|
],
|
|
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
|
|
});
|
|
} catch (err) {
|
|
console.error(`Error processing markdown for ${relPath}:`, err);
|
|
processedContent = `<div class="error-message">
|
|
<p>Error processing markdown content. Please check the console for details.</p>
|
|
<pre>${err instanceof Error ? err.message : 'Unknown error'}</pre>
|
|
</div>`;
|
|
}
|
|
|
|
return {
|
|
type: 'post',
|
|
slug: relPath.replace(/\.md$/, ''),
|
|
title: data.title,
|
|
date: data.date,
|
|
tags: data.tags || [],
|
|
summary: data.summary,
|
|
content: processedContent,
|
|
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) {
|
|
console.error('Error loading posts:', error);
|
|
return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
|
|
}
|
|
}
|
|
|