Files
blog/write-server/src/app/api/posts/route.ts
T

47 lines
1.5 KiB
TypeScript
Raw Normal View History

2026-06-21 20:42:44 +08:00
import { NextRequest, NextResponse } from "next/server";
import { listPosts, createPost, getPostCount } from "@/lib/posts";
import { cleanExpired } from "@/lib/recycle";
export async function GET(request: NextRequest) {
try {
cleanExpired(); // housekeeping on each request
const { searchParams } = request.nextUrl;
const search = searchParams.get("search") || "";
const page = parseInt(searchParams.get("page") || "1", 10);
const perPage = parseInt(searchParams.get("perPage") || "20", 10);
const includeDrafts = searchParams.get("includeDrafts") !== "false";
const result = listPosts({ search, page, perPage, includeDrafts });
const totalCount = getPostCount();
return NextResponse.json({ ...result, totalCount });
} catch (error: unknown) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { frontMatter, content } = body;
if (!frontMatter?.title || !frontMatter?.slug) {
return NextResponse.json(
{ error: "Title and slug are required" },
{ status: 400 }
);
}
const dirPath = createPost(frontMatter, content || "");
return NextResponse.json({ success: true, dirPath }, { status: 201 });
} catch (error: unknown) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
{ status: 500 }
);
}
}