-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbapi.ts
More file actions
65 lines (54 loc) · 1.35 KB
/
bapi.ts
File metadata and controls
65 lines (54 loc) · 1.35 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Backend API (BAPI) client.
* Thin HTTP wrapper for Clerk's Backend API endpoints.
*/
import { getBapiBaseUrl } from "../../lib/environment.ts";
import { normalizeBapiPath } from "../../lib/bapi-command.ts";
import { BapiError } from "../../lib/errors.ts";
import { loggedFetch } from "../../lib/fetch.ts";
export interface BapiResponse {
status: number;
headers: Headers;
body: unknown;
rawBody: string;
}
export async function bapiRequest(options: {
method: string;
path: string;
secretKey: string;
body?: string;
baseUrl?: string;
}): Promise<BapiResponse> {
const base = options.baseUrl ?? getBapiBaseUrl();
const path = normalizeBapiPath(options.path);
const url = `${base}${path}`;
const headers: Record<string, string> = {
Authorization: `Bearer ${options.secretKey}`,
Accept: "application/json",
};
if (options.body) {
headers["Content-Type"] = "application/json";
}
const response = await loggedFetch(url, {
tag: "bapi",
method: options.method,
headers,
body: options.body,
});
if (!response.ok) {
throw await BapiError.fromResponse(response);
}
const rawBody = await response.text();
let body: unknown;
try {
body = JSON.parse(rawBody);
} catch {
body = rawBody;
}
return {
status: response.status,
headers: response.headers,
body,
rawBody,
};
}