diff --git a/app/utils/headscale.ts b/app/utils/headscale.ts index d7e1e2f..86548ae 100644 --- a/app/utils/headscale.ts +++ b/app/utils/headscale.ts @@ -8,36 +8,51 @@ export class HeadscaleError extends Error { } } +export class FatalError extends Error { + constructor(message: string) { + super(message) + this.name = 'FatalError' + } +} + /* eslint-disable @typescript-eslint/no-non-null-assertion */ export async function pull(url: string, key: string) { - const prefix = process.env.HEADSCALE_URL! - const response = await fetch(`${prefix}/api/${url}`, { - headers: { - Authorization: `Bearer ${key}` + try { + const prefix = process.env.HEADSCALE_URL! + const response = await fetch(`${prefix}/api/${url}`, { + headers: { + Authorization: `Bearer ${key}` + } + }) + + if (!response.ok) { + throw new HeadscaleError(await response.text(), response.status) } - }) - if (!response.ok) { - throw new HeadscaleError(await response.text(), response.status) + return await (response.json() as Promise) + } catch { + throw new FatalError('The Headscale server is not reachable') } - - return response.json() as Promise } export async function post(url: string, key: string, body?: unknown) { - const prefix = process.env.HEADSCALE_URL! - const response = await fetch(`${prefix}/api/${url}`, { - method: 'POST', - body: body ? JSON.stringify(body) : undefined, - headers: { - Authorization: `Bearer ${key}` + try { + const prefix = process.env.HEADSCALE_URL! + const response = await fetch(`${prefix}/api/${url}`, { + method: 'POST', + body: body ? JSON.stringify(body) : undefined, + headers: { + Authorization: `Bearer ${key}` + } + }) + + if (!response.ok) { + throw new HeadscaleError(await response.text(), response.status) } - }) - if (!response.ok) { - throw new HeadscaleError(await response.text(), response.status) + return await (response.json() as Promise) + } catch { + throw new FatalError('The Headscale server is not reachable') } - - return response.json() as Promise }