import { desc, asc, eq, like, or, sql } from 'drizzle-orm' import { useDB, schema } from '../../utils/db.js' import { requireAdmin } from '../../utils/auth.js' import { parsePagination } from '../../utils/pagination.js' export default defineEventHandler(async (event) => { requireAdmin(event) const db = useDB() const query = getQuery(event) const { page, limit, offset, search } = parsePagination(event) const type = query.type || 'news' // 基础条件 const conditions = [eq(schema.articles.type, type)] // 搜索 if (search) { conditions.push( or( like(schema.articles.title, `%${search}%`), like(schema.articles.summary, `%${search}%`), like(schema.articles.category, `%${search}%`) ) ) } // 总数 const [{ count: total }] = db .select({ count: sql`count(*)` }) .from(schema.articles) .where(sql`${conditions.reduce((a, b) => sql`${a} AND ${b}`)}`) .all() // 分页数据 const items = db .select() .from(schema.articles) .where(sql`${conditions.reduce((a, b) => sql`${a} AND ${b}`)}`) .orderBy(desc(schema.articles.id)) .limit(limit) .offset(offset) .all() return { items, total, page, limit, totalPages: Math.ceil(total / limit), } })