feat: harden analytics dashboard

This commit is contained in:
2026-05-27 15:19:31 +08:00
parent 5e0ca6a504
commit 356039d9cf
34 changed files with 1424 additions and 879 deletions

View File

@@ -1,22 +1,31 @@
import { NextRequest, NextResponse } from "next/server";
import { jsonError, parseOptionalInt, parseTimestampRange } from "@/lib/api-params";
import { getTrends, type TrendGranularity } from "@/lib/queries";
const GRANULARITIES: TrendGranularity[] = ["hour", "day", "week", "month"];
export async function GET(req: NextRequest) {
const sp = req.nextUrl.searchParams;
const requestedGranularity = sp.get("granularity");
const granularity = GRANULARITIES.includes(requestedGranularity as TrendGranularity)
? requestedGranularity as TrendGranularity
: "day";
const startTs = sp.get("start") ? Number(sp.get("start")) : undefined;
const endTs = sp.get("end") ? Number(sp.get("end")) : undefined;
const channelId = sp.get("channel_id") ? Number(sp.get("channel_id")) : undefined;
try {
const sp = req.nextUrl.searchParams;
const requestedGranularity = sp.get("granularity");
const granularity = GRANULARITIES.includes(requestedGranularity as TrendGranularity)
? requestedGranularity as TrendGranularity
: "day";
const range = parseTimestampRange(sp);
if (!range.ok) return jsonError(range.field);
const data = await getTrends(granularity, startTs, endTs, {
username: sp.get("username") || undefined,
model: sp.get("model") || undefined,
channelId: Number.isFinite(channelId) ? channelId : undefined,
});
return NextResponse.json(data);
const channelId = parseOptionalInt(sp.get("channel_id"), "channel_id");
if (!channelId.ok) return jsonError(channelId.field);
if (channelId.value === 0) return jsonError("channel_id");
const data = await getTrends(granularity, range.value.startTs, range.value.endTs, {
username: sp.get("username") || undefined,
model: sp.get("model") || undefined,
channelId: channelId.value,
});
return NextResponse.json(data);
} catch (error) {
console.error("Failed to load trends", error);
return jsonError(undefined, 500);
}
}