forked from weroperking/Betterbase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-client.ts
More file actions
35 lines (29 loc) · 924 Bytes
/
Copy pathapi-client.ts
File metadata and controls
35 lines (29 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { loadCredentials } from "./credentials";
import { error } from "./logger";
export function requireAuth(): { token: string; serverUrl: string } {
const creds = loadCredentials();
if (!creds?.token) {
error("Not logged in. Run `bb login` first.");
process.exit(1);
}
return { token: creds.token, serverUrl: creds.server_url };
}
export async function apiRequest<T = unknown>(path: string, options: RequestInit = {}): Promise<T> {
const { token, serverUrl } = requireAuth();
const url = `${serverUrl}${path}`;
const res = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
...(options.headers ?? {}),
},
});
if (!res.ok) {
const body = (await res.json().catch(() => ({ error: "Request failed" }))) as {
error?: string;
};
throw new Error(body.error ?? `HTTP ${res.status}`);
}
return res.json() as Promise<T>;
}