feat: harden analytics dashboard
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user