-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
77 lines (70 loc) · 1.99 KB
/
client.ts
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
66
67
68
69
70
71
72
73
74
75
76
77
import { RateLimitter } from "./_rate_limitter.ts";
import { toCamelCaseDeep } from "./_util.ts";
export class RequestError extends Error {
constructor(
public readonly status: number,
public readonly statusText: string,
public readonly body: string,
) {
super(`API request error: ${status} - ${statusText}: ${body}`);
this.name = this.constructor.name;
}
}
export type Credential = {
readonly domain: string;
readonly token: string;
};
export type ClientRequestOptions = {
ignoreRateLimit?: boolean;
skipCaseTransform?: boolean;
};
export class Client {
readonly domain: string;
#token: string;
#baseUrl = new URL("https://api.docbase.io");
constructor(
credential: Credential,
{ baseUrl }: { baseUrl?: URL } = {},
) {
this.domain = credential.domain;
this.#token = credential.token;
this.#baseUrl = baseUrl ?? this.#baseUrl;
}
fetch(
path: string,
init?: RequestInit,
): Promise<Response> {
return fetch(
`${this.#baseUrl}teams/${this.domain}/${path}`,
{
...(init ?? {}),
headers: {
...(init?.headers ?? {}),
"Content-Type": "application/json",
"X-Api-Version": "2",
"X-DocBaseToken": this.#token,
},
},
);
}
async request<T>(
path: string,
init?: RequestInit,
options?: ClientRequestOptions,
): Promise<T> {
const resp = await this.fetch(path, init);
if (resp.ok) {
if (resp.status === 204) {
return undefined as T;
}
const data = await resp.json();
return options?.skipCaseTransform ? data : toCamelCaseDeep(data);
} else if (resp.status === 429 && !options?.ignoreRateLimit) {
await resp.body?.cancel();
const rateLimitter = RateLimitter.fromResponse(resp);
await rateLimitter.wait({ signal: init?.signal ?? undefined });
return this.request(path, init, { ignoreRateLimit: true });
}
throw new RequestError(resp.status, resp.statusText, await resp.text());
}
}