Files

32 lines
1.2 KiB
TypeScript

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) {
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 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);
}
}