31 lines
1.1 KiB
TypeScript
31 lines
1.1 KiB
TypeScript
import type { HeadscaleServiceWidget } from "@/lib/config/schema";
|
|||
|
|
import type { ServiceStat } from "@/lib/types/service-result";
|
||
|
|
import { serviceBaseUrl } from "./base-url";
|
||
|
|
|
||
|
|
async function fetchList(url: string, apiToken: string, label: string, key: "users" | "nodes"): Promise<unknown[]> {
|
||
|
|
const response = await fetch(url, {
|
||
|
|
headers: { Authorization: `Bearer ${apiToken}` },
|
||
|
|
signal: AbortSignal.timeout(5_000),
|
||
|
|
});
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error(`Headscale ${label} API returned ${response.status}`);
|
||
|
|
}
|
||
|
|
const body = (await response.json()) as Record<string, unknown[]>;
|
||
|
|
return body[key] ?? [];
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function collectHeadscale(widget: HeadscaleServiceWidget): Promise<{ stats: ServiceStat[] }> {
|
||
|
|
const base = serviceBaseUrl(widget);
|
||
|
|
const [users, nodes] = await Promise.all([
|
||
|
|
fetchList(`${base}/api/v1/user`, widget.apiToken, "user", "users"),
|
||
|
|
fetchList(`${base}/api/v1/node`, widget.apiToken, "node", "nodes"),
|
||
|
|
]);
|
||
|
|
|
||
|
|
return {
|
||
|
|
stats: [
|
||
|
|
{ label: "Users", value: String(users.length) },
|
||
|
|
{ label: "Nodes", value: String(nodes.length) },
|
||
|
|
],
|
||
|
|
};
|
||
|
|
}
|