fix: handle a case when headscale is unreachable
This commit is contained in:
parent
27f310fb35
commit
8148e242dc
@ -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 */
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
|
||||||
export async function pull<T>(url: string, key: string) {
|
export async function pull<T>(url: string, key: string) {
|
||||||
const prefix = process.env.HEADSCALE_URL!
|
try {
|
||||||
const response = await fetch(`${prefix}/api/${url}`, {
|
const prefix = process.env.HEADSCALE_URL!
|
||||||
headers: {
|
const response = await fetch(`${prefix}/api/${url}`, {
|
||||||
Authorization: `Bearer ${key}`
|
headers: {
|
||||||
|
Authorization: `Bearer ${key}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new HeadscaleError(await response.text(), response.status)
|
||||||
}
|
}
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
return await (response.json() as Promise<T>)
|
||||||
throw new HeadscaleError(await response.text(), response.status)
|
} catch {
|
||||||
|
throw new FatalError('The Headscale server is not reachable')
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.json() as Promise<T>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function post<T>(url: string, key: string, body?: unknown) {
|
export async function post<T>(url: string, key: string, body?: unknown) {
|
||||||
const prefix = process.env.HEADSCALE_URL!
|
try {
|
||||||
const response = await fetch(`${prefix}/api/${url}`, {
|
const prefix = process.env.HEADSCALE_URL!
|
||||||
method: 'POST',
|
const response = await fetch(`${prefix}/api/${url}`, {
|
||||||
body: body ? JSON.stringify(body) : undefined,
|
method: 'POST',
|
||||||
headers: {
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
Authorization: `Bearer ${key}`
|
headers: {
|
||||||
|
Authorization: `Bearer ${key}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new HeadscaleError(await response.text(), response.status)
|
||||||
}
|
}
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
return await (response.json() as Promise<T>)
|
||||||
throw new HeadscaleError(await response.text(), response.status)
|
} catch {
|
||||||
|
throw new FatalError('The Headscale server is not reachable')
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.json() as Promise<T>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user