mc-dashboard/app/api/analytics/route.ts

57 lines
1.3 KiB
TypeScript
Raw Normal View History

import { NextRequest, NextResponse } from "next/server";
import { readFileSync, existsSync } from "fs";
import { auth } from "@/lib/auth";
export const dynamic = "force-dynamic";
const ANALYTICS_FILE = "/home/minecraft/server/analytics.jsonl";
type MetricEntry = {
ts: string;
tps: number;
ramUsedMB: number;
ramTotalMB: number;
cpuPercent: number;
playersOnline: number;
players: string[];
};
export async function GET(req: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
}
const hours = Math.min(
parseInt(req.nextUrl.searchParams.get("hours") || "6"),
48
);
if (!existsSync(ANALYTICS_FILE)) {
return NextResponse.json([]);
}
try {
const lines = readFileSync(ANALYTICS_FILE, "utf8")
.split("\n")
.filter(Boolean);
const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000).toISOString();
const entries: MetricEntry[] = [];
for (const line of lines) {
try {
const entry = JSON.parse(line) as MetricEntry;
if (entry.ts >= cutoff) entries.push(entry);
} catch {}
}
return NextResponse.json(entries);
} catch (e) {
return NextResponse.json(
{ error: (e as Error).message },
{ status: 500 }
);
}
}