iboard/server/routes/news.js
2026-08-06 15:39:59 +08:00

26 lines
895 B
JavaScript

import { Router } from 'express'
import { prisma } from '../db.js'
import { authRequired } from '../middleware.js'
const router = Router()
router.use(authRequired)
// 新闻列表: 按时间最新优先, cursor 分页 (cursor = publishedAt ISO 字符串)
// 用 prisma cursor 配合 id 兜底 (同一秒发布的新闻)
router.get('/news', async (req, res, next) => {
try {
const limit = Math.min(Number(req.query.limit) || 10, 50)
const cursor = req.query.cursor || null
const where = cursor ? { publishedAt: { lt: new Date(cursor) } } : {}
const items = await prisma.news.findMany({
where,
orderBy: [{ publishedAt: 'desc' }, { id: 'desc' }],
take: limit,
})
const nextCursor = items.length === limit ? items[items.length - 1].publishedAt.toISOString() : null
res.json({ items, nextCursor })
} catch (e) { next(e) }
})
export default router