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

106 lines
2.7 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,
{ params }: { params: { slug: string } }
2024-07-25 22:09:06 +02:00
) => {
const client = await clientPromise;
const db = client.db();
const { slug } = params;
2024-07-23 20:02:57 +02:00
if (!slug) {
return NextResponse.json({ message: "Slug is required" }, { status: 400 });
}
2024-07-23 20:02:57 +02:00
const page = await db.collection("pages").findOne({ slug });
2024-07-25 22:09:06 +02:00
if (page) {
return NextResponse.json(page, { status: 200 });
} else {
return NextResponse.json({ message: "Page not found" }, { status: 404 });
}
2024-07-25 20:29:21 +02:00
};
2024-07-25 22:09:06 +02:00
export const PUT = async (
req: NextRequest,
{ params }: { params: { slug: string } }
2024-07-25 22:09:06 +02:00
) => {
const client = await clientPromise;
const db = client.db();
const { slug } = params;
if (!slug) {
return NextResponse.json({ message: "Slug is required" }, { status: 400 });
}
const { title, content, vulnerabilities } = await req.json();
2024-07-25 22:09:06 +02:00
if (
typeof title !== "string" ||
typeof content !== "string" ||
typeof vulnerabilities !== "string"
) {
return NextResponse.json(
{ message: "Invalid title, content, or vulnerabilities" },
{ status: 400 }
);
}
try {
const result = await db.collection("pages").findOneAndUpdate(
{ slug },
{ $set: { title, content, vulnerabilities } },
{ returnDocument: "after" } // Updated option
);
2024-07-25 22:09:06 +02:00
if (result?.value) {
const serializedResult = {
...result.value,
_id: result.value._id.toString() // Convert ObjectId to string
};
return NextResponse.json(serializedResult, { status: 200 });
} else {
return NextResponse.json({ message: "Page not found" }, { status: 404 });
}
} catch (error) {
console.error("Error updating page:", error);
return NextResponse.json(
{ message: "Failed to update page" },
{ status: 500 }
);
}
2024-07-25 22:09:06 +02:00
};
export const DELETE = async (
req: NextRequest,
{ params }: { params: { slug: string } }
2024-07-25 22:09:06 +02:00
) => {
const client = await clientPromise;
const db = client.db();
const { slug } = params;
2024-07-25 22:09:06 +02:00
if (!slug) {
return NextResponse.json({ message: "Slug is required" }, { status: 400 });
}
2024-07-25 22:09:06 +02:00
try {
const result = await db.collection("pages").deleteOne({ slug });
2024-07-25 22:09:06 +02:00
if (result.deletedCount > 0) {
return NextResponse.json(
{ message: "Page deleted successfully" },
{ status: 200 }
);
} else {
return NextResponse.json({ message: "Page not found" }, { status: 404 });
}
} catch (error) {
console.error("Error deleting page:", error);
return NextResponse.json(
{ message: "Failed to delete page" },
{ status: 500 }
);
}
};