aboutsummaryrefslogtreecommitdiff
path: root/fe/src/http.ts
diff options
context:
space:
mode:
Diffstat (limited to 'fe/src/http.ts')
-rw-r--r--fe/src/http.ts92
1 files changed, 92 insertions, 0 deletions
diff --git a/fe/src/http.ts b/fe/src/http.ts
new file mode 100644
index 0000000..3b2a4f0
--- /dev/null
+++ b/fe/src/http.ts
@@ -0,0 +1,92 @@
1let instance;
2const baseUrl = import.meta.env?.VITE_API_BASE_URL ?? "http://localhost:8080/api/v1";
3
4class HttpClient {
5 baseURL: string;
6 commonHeaders: Headers;
7
8 constructor(baseURL: string) {
9 this.baseURL = baseURL;
10 this.commonHeaders = new Headers({
11 "Content-Type": "application/json"
12 })
13 if (instance) {
14 throw new Error("New instance cannot be created!");
15 }
16
17 instance = this;
18 }
19
20 private getURL(endpoint: string): URL {
21 return new URL(endpoint, this.baseURL);
22 }
23
24 private token(): string | null {
25 return localStorage.getItem('token');
26 }
27
28 private async makeRequest(request: Request): Promise<Response> {
29 return fetch(request)
30 }
31
32 async get({ endpoint, headers }: IHttpParameters): Promise<Response> {
33 const url: URL = this.getURL(endpoint);
34 headers = Object.assign<Headers, Headers>(headers, this.commonHeaders);
35 const request: Request = new Request(url, {
36 method: "GET",
37 headers
38 });
39
40 return this.makeRequest(request);
41 }
42
43 async post({ endpoint, authenticated, body, headers }: IHttpParameters): Promise<Response> {
44 const url = this.getURL(endpoint);
45
46 if (authenticated) {
47 const token: string | null = this.token();
48 headers.append('Authorization', `Bearer ${token}`);
49 }
50
51 const request: Request = new Request(url, {
52 method: "POST",
53 body: JSON.stringify(body),
54 headers
55 })
56
57 return this.makeRequest(request);
58 }
59
60 async patch({ endpoint, authenticated, headers }: IHttpParameters): Promise<Response> {
61 const url = this.getURL(endpoint);
62 if (authenticated) {
63
64 }
65 const response: Response = await fetch(url, {
66 method: "PATCH",
67 headers
68 });
69 }
70
71 async delete({ endpoint, authenticated, headers }: IHttpParameters): Promise<Response> {
72 const url = this.getURL(endpoint);
73 if (authenticated) {
74
75 }
76 const response: Response = await fetch(url, {
77 method: "DELETE",
78 headers
79 })
80 }
81}
82
83interface IHttpParameters {
84 endpoint: string;
85 body: Record<string, any>;
86 authenticated: boolean;
87 headers: Headers;
88}
89
90let http: Readonly<HttpClient> = Object.freeze(new HttpClient(baseUrl));
91
92export default http;