import { count, desc } from "drizzle-orm"; import { apiJson, pagination } from "@/lib/api"; import { db, WebsiteArticles } from "@/lib/db"; /** * GET /api/articles — paginated list of website_articles, newest first. * Mirrors the /news page query. Returns list cards (shortStory only, never * fullStory) plus pagination metadata. */ export async function GET(req: Request) { const sp = new URL(req.url).searchParams; const { page, perPage, skip, take } = pagination(sp); try { const [totalRows, articles] = await Promise.all([ db.select({ total: count() }).from(WebsiteArticles), db .select({ id: WebsiteArticles.id, title: WebsiteArticles.title, slug: WebsiteArticles.slug, shortStory: WebsiteArticles.shortStory, image: WebsiteArticles.image, createdAt: WebsiteArticles.createdAt, }) .from(WebsiteArticles) .orderBy(desc(WebsiteArticles.createdAt)) .limit(take) .offset(skip), ]); const total = totalRows[0]?.total ?? 0; return apiJson({ data: articles, meta: { page, perPage, total, lastPage: Math.max(1, Math.ceil(total / perPage)), }, }); } catch { // DB unavailable — return an empty payload instead of a 500. return apiJson( { data: [], meta: { page, perPage, total: 0, lastPage: 1 } }, { status: 200 }, ); } }