75 lines
1.6 KiB
TypeScript
75 lines
1.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
// Example API route for chat messages
|
|
// Access at: /api/chat/messages
|
|
|
|
// In-memory storage (replace with a real database)
|
|
let messages: Array<{
|
|
id: string;
|
|
username: string;
|
|
message: string;
|
|
timestamp: string;
|
|
}> = [];
|
|
|
|
export async function GET(request: NextRequest) {
|
|
// Return recent chat messages
|
|
return NextResponse.json({
|
|
messages: messages.slice(-100), // Last 100 messages
|
|
});
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const { username, message } = body;
|
|
|
|
// Basic validation
|
|
if (!username || !message) {
|
|
return NextResponse.json(
|
|
{ error: 'Username and message required' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
if (message.length > 500) {
|
|
return NextResponse.json(
|
|
{ error: 'Message too long' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Create new message
|
|
const newMessage = {
|
|
id: Math.random().toString(36).substring(7),
|
|
username,
|
|
message,
|
|
timestamp: new Date().toISOString(),
|
|
};
|
|
|
|
messages.push(newMessage);
|
|
|
|
// Keep only last 1000 messages
|
|
if (messages.length > 1000) {
|
|
messages = messages.slice(-1000);
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: newMessage,
|
|
});
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ error: 'Failed to post message' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function DELETE(request: NextRequest) {
|
|
// Clear all messages (admin only)
|
|
messages = [];
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: 'Chat cleared',
|
|
});
|
|
}
|