File size: 2,204 Bytes
e454383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Import necessary types from TypeScript and fetch API
const port = 8000;
// const baseUrl = `https://obscure-spork-jr94576rpr53wgg-8000.app.github.dev/api/v1`;
// const baseUrl = `http://localhost:${port}/api/v1`;
const baseUrl = `/api/v1`;
// Define types for the request function parameters
type RequestMethod = "GET" | "POST" | "PUT" | "DELETE";

interface RequestHeaders {
  [key: string]: string;
}

interface RequestOptions {
  method: RequestMethod;
  url: string;
  data?: any; // Data can be of any type, though usually it's JSON or FormData
  headers?: RequestHeaders;
  bearerToken?: string | null;
}

// Utility function to handle requests
export async function request(
  method: RequestMethod,
  url: string,
  data: any = null,
  headers: RequestHeaders = {},
  bearerToken: string | null = null
): Promise<Response> {
  url = baseUrl + url;

  // Define headers and options for the fetch API
  let fetchOptions: RequestInit = {
    method: method,
    headers: {
      "Content-Type": "application/json",
      Authorization: bearerToken ? `Bearer ${bearerToken}` : "",
      ...headers,
    },
  };

  // Adjust the Content-Type if data is FormData
  if (data instanceof FormData) {
    delete (fetchOptions.headers as Record<string, string>)["Content-Type"];
  }

  // Set request body if data is present
  if (data !== null) {
    fetchOptions.body = data instanceof FormData ? data : JSON.stringify(data);
  }

  // Send the request and return the fetch response
  return fetch(url, fetchOptions);
}

// Define individual HTTP method functions
export function get(
  url: string,
  headers?: RequestHeaders,
  bearerToken?: string
) {
  return request("GET", url, null, headers, bearerToken);
}

export function post(
  url: string,
  data: any,
  headers?: RequestHeaders,
  bearerToken?: string
) {
  return request("POST", url, data, headers, bearerToken);
}

export function put(
  url: string,
  data: any,
  headers?: RequestHeaders,
  bearerToken?: string
) {
  return request("PUT", url, data, headers, bearerToken);
}

export function del(
  url: string,
  headers?: RequestHeaders,
  bearerToken?: string
) {
  return request("DELETE", url, null, headers, bearerToken);
}