- Refactor multiple API routes to utilize a centralized configuration function for base URL and token management, improving code consistency and maintainability. - Replace direct environment variable access with a unified config function in the `lib/api.ts` file. - Remove redundant error handling and streamline response handling in various API endpoints. - Delete unused job-related API routes and settings, simplifying the overall API structure.
75 lines
1.9 KiB
TypeScript
75 lines
1.9 KiB
TypeScript
import { NextRequest } from "next/server";
|
|
import { config } from "@/lib/api";
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const { baseUrl, token } = config();
|
|
|
|
const stream = new ReadableStream({
|
|
async start(controller) {
|
|
controller.enqueue(new TextEncoder().encode(""));
|
|
|
|
let lastData: string | null = null;
|
|
let isActive = true;
|
|
|
|
const fetchJobs = async () => {
|
|
if (!isActive) return;
|
|
|
|
try {
|
|
const response = await fetch(`${baseUrl}/index/status`, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
|
|
if (response.ok && isActive) {
|
|
const data = await response.json();
|
|
const dataStr = JSON.stringify(data);
|
|
|
|
// Send if data changed
|
|
if (dataStr !== lastData && isActive) {
|
|
lastData = dataStr;
|
|
try {
|
|
controller.enqueue(
|
|
new TextEncoder().encode(`data: ${dataStr}\n\n`)
|
|
);
|
|
} catch (err) {
|
|
// Controller closed, ignore
|
|
isActive = false;
|
|
}
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (isActive) {
|
|
console.error("SSE fetch error:", error);
|
|
}
|
|
}
|
|
};
|
|
|
|
// Initial fetch
|
|
await fetchJobs();
|
|
|
|
// Poll every 2 seconds
|
|
const interval = setInterval(async () => {
|
|
if (!isActive) {
|
|
clearInterval(interval);
|
|
return;
|
|
}
|
|
await fetchJobs();
|
|
}, 2000);
|
|
|
|
// Cleanup
|
|
request.signal.addEventListener("abort", () => {
|
|
isActive = false;
|
|
clearInterval(interval);
|
|
controller.close();
|
|
});
|
|
},
|
|
});
|
|
|
|
return new Response(stream, {
|
|
headers: {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache",
|
|
"Connection": "keep-alive",
|
|
},
|
|
});
|
|
}
|