47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
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 }
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|