lesssagoo

This commit is contained in:
rattatwinko
2025-06-16 17:06:26 +02:00
parent 037c7cd31e
commit 439d673e8f
9 changed files with 323 additions and 52 deletions

View File

@@ -0,0 +1,61 @@
import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { remark } from 'remark';
import html from 'remark-html';
const postsDirectory = path.join(process.cwd(), 'posts');
// Function to get file creation date
function getFileCreationDate(filePath: string): Date {
const stats = fs.statSync(filePath);
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');
const { data, content } = matter(fileContents);
const createdAt = getFileCreationDate(fullPath);
const processedContent = await remark()
.use(html)
.process(content);
return {
slug: realSlug,
title: data.title,
date: data.date,
tags: data.tags || [],
summary: data.summary,
content: processedContent.toString(),
createdAt: createdAt.toISOString(),
};
}
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()
);
}
export async function GET() {
try {
const posts = await getAllPosts();
return NextResponse.json(posts);
} catch (error) {
return NextResponse.json({ error: 'Failed to fetch posts' }, { status: 500 });
}
}