2024-07-20 21:04:38 +02:00
|
|
|
import { NextRequest, NextResponse } from "next/server";
|
2024-07-20 21:37:40 +02:00
|
|
|
import { promises as fs } from "fs";
|
2024-07-20 21:04:38 +02:00
|
|
|
import path from "path";
|
|
|
|
import matter from "gray-matter";
|
|
|
|
|
2024-07-20 21:37:40 +02:00
|
|
|
const changelogsDir = path.resolve(process.cwd(), "data/pages");
|
2024-07-20 21:04:38 +02:00
|
|
|
|
2024-07-20 21:37:40 +02:00
|
|
|
async function getMDXFiles(dir: string): Promise<string[]> {
|
|
|
|
const files = await fs.readdir(dir);
|
|
|
|
return files.filter((file) => file.endsWith(".mdx"));
|
2024-07-20 21:04:38 +02:00
|
|
|
}
|
|
|
|
|
2024-07-20 21:37:40 +02:00
|
|
|
export async function GET() {
|
2024-07-20 21:04:38 +02:00
|
|
|
try {
|
2024-07-20 21:37:40 +02:00
|
|
|
const mdxFiles = await getMDXFiles(changelogsDir);
|
|
|
|
const pages = await Promise.all(
|
|
|
|
mdxFiles.map(async (file) => {
|
|
|
|
const filePath = path.join(changelogsDir, file);
|
|
|
|
const content = await fs.readFile(filePath, "utf-8");
|
|
|
|
const { data, content: mdxContent } = matter(content);
|
|
|
|
const slug = path.basename(file, path.extname(file));
|
|
|
|
return {
|
|
|
|
metadata: data,
|
|
|
|
slug,
|
|
|
|
content: mdxContent,
|
|
|
|
};
|
|
|
|
})
|
|
|
|
);
|
|
|
|
return NextResponse.json(pages, { status: 200 });
|
2024-07-20 21:04:38 +02:00
|
|
|
} catch (error) {
|
2024-07-20 21:37:40 +02:00
|
|
|
console.error("Failed to fetch pages:", error);
|
2024-07-20 21:04:38 +02:00
|
|
|
return NextResponse.json(
|
2024-07-20 21:37:40 +02:00
|
|
|
{ error: "Failed to fetch pages" },
|
2024-07-20 21:04:38 +02:00
|
|
|
{ status: 500 }
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-20 21:37:40 +02:00
|
|
|
export async function POST(request: NextRequest) {
|
|
|
|
const { title } = await request.json();
|
|
|
|
const slug = title.toLowerCase().replace(/\s+/g, "-");
|
|
|
|
const filePath = path.join(changelogsDir, `${slug}.mdx`);
|
2024-07-20 21:04:38 +02:00
|
|
|
|
|
|
|
try {
|
2024-07-20 21:37:40 +02:00
|
|
|
if (
|
|
|
|
await fs
|
|
|
|
.stat(filePath)
|
|
|
|
.then(() => true)
|
|
|
|
.catch(() => false)
|
|
|
|
) {
|
|
|
|
return NextResponse.json(
|
|
|
|
{ error: "Page already exists" },
|
|
|
|
{ status: 400 }
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
await fs.writeFile(filePath, `---\ntitle: ${title}\n---\n`);
|
|
|
|
return NextResponse.json({ title, slug }, { status: 201 });
|
2024-07-20 21:04:38 +02:00
|
|
|
} catch (error) {
|
2024-07-20 21:37:40 +02:00
|
|
|
console.error("Failed to create page:", error);
|
2024-07-20 21:04:38 +02:00
|
|
|
return NextResponse.json(
|
2024-07-20 21:37:40 +02:00
|
|
|
{ error: "Failed to create page" },
|
2024-07-20 21:04:38 +02:00
|
|
|
{ status: 500 }
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|