-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathApi.ts
More file actions
63 lines (61 loc) · 1.72 KB
/
Api.ts
File metadata and controls
63 lines (61 loc) · 1.72 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
export class ApiError extends Error {
response: Response;
constructor(
response: Response,
message?: string | undefined,
options?: ErrorOptions | undefined,
...other: unknown[]
) {
super(message, options, ...(other as []));
this.response = response;
}
}
export class Api {
baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
getFetchConfig = (config: RequestInit) => {
const headers = {
"Content-Type": "application/json",
...(config?.headers || {}),
};
const requestInit: RequestInit = {
...config,
headers,
};
return requestInit;
};
async request(
method: string = "GET",
endpoint: string,
data: unknown,
config: RequestInit
) {
const url = new URL(endpoint, this.baseUrl).toString();
const response = await fetch(url, {
body: data ? JSON.stringify(data) : undefined,
method,
headers: {
...config.headers,
},
});
if (!response.ok) {
throw new ApiError(response, "Failed Api Request for " + endpoint);
}
const jsonData = await response.json();
return { data: jsonData };
}
async post(endpoint: string, data: any, config: RequestInit = {}) {
return this.request("POST", endpoint, data, this.getFetchConfig(config));
}
async get(endpoint: string, config: RequestInit = {}) {
return this.request("GET", endpoint, null, this.getFetchConfig(config));
}
async put(endpoint: string, data: any, config: RequestInit = {}) {
return this.request("PUT", endpoint, data, this.getFetchConfig(config));
}
async delete(endpoint: string, config: RequestInit = {}) {
return this.request("DELETE", endpoint, null, this.getFetchConfig(config));
}
}