59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { listPosts, createPost, getPostCount } from "@/lib/posts";
|
|
import { cleanExpired } from "@/lib/recycle";
|
|
import { getAuthFromRequest } from "@/lib/auth";
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
cleanExpired();
|
|
|
|
const user = getAuthFromRequest(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 author = user?.role === "admin" ? undefined : user?.name;
|
|
|
|
const result = listPosts({ search, page, perPage, includeDrafts, author });
|
|
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 user = getAuthFromRequest(request);
|
|
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 }
|
|
);
|
|
}
|
|
|
|
// 自动设置作者为当前登录用户
|
|
if (user) {
|
|
frontMatter.author = user.name;
|
|
}
|
|
|
|
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 }
|
|
);
|
|
}
|
|
}
|