homelab-dashboard/src/app/api/status/route.ts
Bilal Teke b2d2b8b2f3 v3.1
2026-04-15 21:54:46 +02:00

67 lines
No EOL
1.7 KiB
TypeScript

import { NextResponse } from 'next/server';
import { services } from '@/src/data/services';
import { ServiceCheckResult } from '@/src/types/service';
export const dynamic = 'force-dynamic';
async function checkService(service: typeof services[0]): Promise<ServiceCheckResult> {
const startTime = Date.now();
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
const response = await fetch(service.monitorUrl, {
method: 'HEAD', // Use HEAD to minimize data transfer
cache: 'no-store',
signal: controller.signal,
});
clearTimeout(timeoutId);
const responseTime = Date.now() - startTime;
let status: ServiceCheckResult['status'];
if (response.ok) {
status = responseTime <= 2000 ? 'online' : 'warning';
} else if (response.status >= 400 && response.status < 500) {
status = 'warning';
} else {
status = 'offline';
}
return {
id: service.id,
status,
responseTimeMs: responseTime,
httpStatus: response.status,
checkedAt: new Date().toISOString(),
};
} catch (error) {
const responseTime = Date.now() - startTime;
return {
id: service.id,
status: 'offline',
responseTimeMs: responseTime,
httpStatus: null,
checkedAt: new Date().toISOString(),
};
}
}
export async function GET() {
try {
const results = await Promise.all(
services.map(service => checkService(service))
);
return NextResponse.json(results);
} catch (error) {
console.error('Error checking services:', error);
return NextResponse.json(
{ error: 'Failed to check services' },
{ status: 500 }
);
}
}