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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
let instance;
const baseUrl = import.meta.env?.VITE_API_BASE_URL ?? "http://localhost:8080/api/v1";
class HttpClient {
baseURL: string;
commonHeaders: Headers;
constructor(baseURL: string) {
this.baseURL = baseURL;
this.commonHeaders = new Headers({
"Content-Type": "application/json"
})
if (instance) {
throw new Error("New instance cannot be created!");
}
instance = this;
}
private getURL(endpoint: string): URL {
return new URL(endpoint, this.baseURL);
}
private token(): string | null {
return localStorage.getItem('token');
}
private async makeRequest(request: Request): Promise<Response> {
return fetch(request)
}
async get({ endpoint, headers }: IHttpParameters): Promise<Response> {
const url: URL = this.getURL(endpoint);
headers = Object.assign<Headers, Headers>(headers, this.commonHeaders);
const request: Request = new Request(url, {
method: "GET",
headers
});
return this.makeRequest(request);
}
async post({ endpoint, authenticated, body, headers }: IHttpParameters): Promise<Response> {
const url = this.getURL(endpoint);
if (authenticated) {
const token: string | null = this.token();
headers.append('Authorization', `Bearer ${token}`);
}
const request: Request = new Request(url, {
method: "POST",
body: JSON.stringify(body),
headers
})
return this.makeRequest(request);
}
async patch({ endpoint, authenticated, headers }: IHttpParameters): Promise<Response> {
const url = this.getURL(endpoint);
if (authenticated) {
}
const response: Response = await fetch(url, {
method: "PATCH",
headers
});
}
async delete({ endpoint, authenticated, headers }: IHttpParameters): Promise<Response> {
const url = this.getURL(endpoint);
if (authenticated) {
}
const response: Response = await fetch(url, {
method: "DELETE",
headers
})
}
}
interface IHttpParameters {
endpoint: string;
body: Record<string, any>;
authenticated: boolean;
headers: Headers;
}
let http: Readonly<HttpClient> = Object.freeze(new HttpClient(baseUrl));
export default http;
|