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

52 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { sendCommand } from "@/lib/rcon";
import { readChatMessages } from "@/lib/chat-log";
export const dynamic = "force-dynamic";
export async function GET(req: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
}
const maxLines = parseInt(req.nextUrl.searchParams.get("lines") || "100");
try {
return NextResponse.json(readChatMessages(maxLines));
} catch (e) {
return NextResponse.json(
{ error: (e as Error).message },
{ status: 500 }
);
}
}
export async function POST(req: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
}
const { message } = await req.json();
if (!message || typeof message !== "string" || message.length > 256) {
return NextResponse.json({ error: "Invalid message" }, { status: 400 });
}
const sanitized = message.replace(/[\r\n]/g, "").trim();
if (!sanitized) {
return NextResponse.json({ error: "Empty message" }, { status: 400 });
}
try {
const response = await sendCommand(`say ${sanitized}`);
return NextResponse.json({ ok: true, response });
} catch (e) {
return NextResponse.json(
{ error: (e as Error).message },
{ status: 500 }
);
}
}