52 lines
1.8 KiB
TypeScript
52 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { config } from "dotenv"
|
|
import { resolve } from "path"
|
|
import { ObjectId } from "mongodb"
|
|
import { getCollection } from "@/lib/db/mongo"
|
|
|
|
if (typeof process !== "undefined" && !process.env.MONGODB_URI) {
|
|
config({ path: resolve(process.cwd(), ".env.local") })
|
|
}
|
|
|
|
const now = () => new Date().toISOString()
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const { searchParams } = new URL(request.url)
|
|
const type = searchParams.get("type") // tag | event | banner | 空=全部
|
|
const coll = await getCollection("contentItems")
|
|
const query = type ? { type } : {}
|
|
const list = await coll.find(query).sort({ sortOrder: 1, createdAt: -1 }).limit(300).toArray()
|
|
const data = list.map((doc: Record<string, unknown> & { _id: ObjectId }) => ({
|
|
...doc,
|
|
id: doc._id.toString(),
|
|
}))
|
|
return NextResponse.json({ success: true, data })
|
|
} catch (e) {
|
|
console.error("GET /api/admin/content/items error:", e)
|
|
return NextResponse.json({ success: false, error: String(e) }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json()
|
|
const coll = await getCollection("contentItems")
|
|
const doc = {
|
|
type: body.type ?? "tag",
|
|
title: body.title ?? "未命名",
|
|
link: body.link ?? "",
|
|
image: body.image ?? "",
|
|
sortOrder: Number(body.sortOrder) || 0,
|
|
status: body.status ?? "active",
|
|
createdAt: now(),
|
|
updatedAt: now(),
|
|
}
|
|
const r = await coll.insertOne(doc)
|
|
return NextResponse.json({ success: true, data: { id: r.insertedId.toString() } })
|
|
} catch (e) {
|
|
console.error("POST /api/admin/content/items error:", e)
|
|
return NextResponse.json({ success: false, error: String(e) }, { status: 500 })
|
|
}
|
|
}
|