svrjs-nextjs-website/app/api/mdx/pages/route.ts

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-07-25 20:29:21 +02:00
import { NextRequest, NextResponse } from "next/server";
2024-07-23 20:02:57 +02:00
import clientPromise from "@/lib/db";
2024-07-25 22:09:06 +02:00
export const GET = async (req: NextRequest) => {
2024-07-25 20:29:21 +02:00
const client = await clientPromise;
const db = client.db();
2024-07-25 22:09:06 +02:00
try {
const pages = await db.collection("pages").find().toArray();
return NextResponse.json(pages, { status: 200 });
} catch (error) {
console.error("Error fetching pages:", error);
return NextResponse.json(
{ message: "Failed to fetch pages" },
{ status: 500 }
);
}
2024-07-25 20:29:21 +02:00
};
export const POST = async (req: NextRequest) => {
const client = await clientPromise;
const db = client.db();
const { title, slug, content } = await req.json();
2024-07-25 22:24:35 +02:00
if (!slug) {
2024-07-23 20:02:57 +02:00
return NextResponse.json(
2024-07-25 22:09:06 +02:00
{ message: "Missing required fields" },
2024-07-25 20:29:21 +02:00
{ status: 400 }
2024-07-23 20:02:57 +02:00
);
}
2024-07-25 20:29:21 +02:00
try {
const newPage = { title, slug, content };
const result = await db.collection("pages").insertOne(newPage);
return NextResponse.json(newPage, { status: 201 });
} catch (error) {
console.error("Error creating page:", error);
return NextResponse.json(
{ message: "Failed to create page" },
{ status: 500 }
);
}
2024-07-25 20:29:21 +02:00
};