Implement Server-Sent Events for real-time updates and enhance API route handling. Added loading state and last update indicator in the home page. Improved folder and post detail fetching logic in the admin page. Added webhook notification on file changes.
Some checks failed
Deploy / build-and-deploy (push) Failing after 2s
Some checks failed
Deploy / build-and-deploy (push) Failing after 2s
This commit is contained in:
57
src/app/api/posts/stream/route.ts
Normal file
57
src/app/api/posts/stream/route.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { watchPosts, stopWatching } from '@/lib/markdown';
|
||||
|
||||
// Prevent static generation of this route
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
// Store connected clients
|
||||
const clients = new Set<ReadableStreamDefaultController>();
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
// Add this client to the set
|
||||
clients.add(controller);
|
||||
|
||||
// Send initial connection message
|
||||
controller.enqueue(`data: ${JSON.stringify({ type: 'connected', message: 'SSE connection established' })}\n\n`);
|
||||
|
||||
// Set up file watcher if not already set up
|
||||
if (clients.size === 1) {
|
||||
watchPosts(() => {
|
||||
// Notify all connected clients about the update
|
||||
const message = JSON.stringify({ type: 'update', timestamp: new Date().toISOString() });
|
||||
clients.forEach(client => {
|
||||
try {
|
||||
client.enqueue(`data: ${message}\n\n`);
|
||||
} catch (error) {
|
||||
// Remove disconnected clients
|
||||
clients.delete(client);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Clean up when client disconnects
|
||||
request.signal.addEventListener('abort', () => {
|
||||
clients.delete(controller);
|
||||
|
||||
// Stop watching if no clients are connected
|
||||
if (clients.size === 0) {
|
||||
stopWatching();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return new NextResponse(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'Cache-Control'
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user