74 lines
1.9 KiB
TypeScript
74 lines
1.9 KiB
TypeScript
// Example: Real-Time Viewer Count with Railway
|
|
// Uses WebSocket to broadcast viewer count updates
|
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
// In-memory viewer count (in production, use Redis or database)
|
|
let viewerCount = Math.floor(Math.random() * 1000) + 100;
|
|
|
|
export async function GET(request: NextRequest) {
|
|
return NextResponse.json({
|
|
viewers: viewerCount,
|
|
timestamp: new Date().toISOString(),
|
|
});
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const { action, count } = body;
|
|
|
|
switch (action) {
|
|
case 'increment':
|
|
viewerCount = Math.max(0, viewerCount + 1);
|
|
break;
|
|
case 'decrement':
|
|
viewerCount = Math.max(0, viewerCount - 1);
|
|
break;
|
|
case 'set':
|
|
if (typeof count === 'number' && count >= 0) {
|
|
viewerCount = count;
|
|
}
|
|
break;
|
|
default:
|
|
return NextResponse.json(
|
|
{ error: 'Invalid action' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// In production: broadcast via WebSocket
|
|
// io.emit('viewer-count-update', viewerCount);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
viewers: viewerCount,
|
|
});
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ error: 'Failed to update viewer count' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
// Production setup with Redis (recommended for Railway):
|
|
/*
|
|
import { Redis } from '@upstash/redis';
|
|
|
|
const redis = new Redis({
|
|
url: process.env.UPSTASH_REDIS_REST_URL,
|
|
token: process.env.UPSTASH_REDIS_REST_TOKEN,
|
|
});
|
|
|
|
// Then use Redis instead of in-memory:
|
|
export async function GET() {
|
|
const viewers = await redis.get('viewer-count') || 0;
|
|
return NextResponse.json({ viewers });
|
|
}
|
|
*/
|
|
|
|
// Redis setup on Railway:
|
|
// 1. Add Upstash Redis service to Railway project
|
|
// 2. Set environment variables
|
|
// 3. Use the client as shown above
|