-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuniversalModule.ts
More file actions
59 lines (47 loc) · 1.83 KB
/
Copy pathuniversalModule.ts
File metadata and controls
59 lines (47 loc) · 1.83 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
// Base API URL
const api = 'https://opentdb.com/';
type Endpoint = string;
// Function to generate a complete URL
const url = (endpoint: Endpoint) => `${api}${endpoint}`;
// Function to create headers for a fetch request
const createHeadersFn = (method: string, data: object | '') => {
const headers = {} as Headers;
headers.method = method;
// headers.headers = {
// 'Content-Type': 'application/json',
// 'Access-Control-Allow-Origin': '*'
// }
// Include the request body for 'PUT' or 'POST' methods
if (method === 'PUT' || method === 'POST') {
headers.body = JSON.stringify(data);
}
return headers;
};
// should have a catch, I dont like await
// Function to perform a fetch request using the specified endpoint and headers
const fetchFn = <T>(endpoint: Endpoint, headers: Headers) => {
return fetch(url(endpoint), headers)
.then(response => response.json())
.then((data: T) => data);
// .catch((error: string) => console.error('Error fetching data:', error));
};
// Function for making a GET request
export const getFunction = <T>(endpoint: Endpoint) => {
const headers = createHeadersFn('GET', '');
return fetchFn<T>(endpoint, headers);
};
// // Function for making a POST request
// export const postFunction = (endpoint: Endpoint, body: object) => {
// const headers = createHeadersFn('POST', body);
// return fetchFn(endpoint, headers);
// }
// // Function for making a PUT request
// export const putFunction = (endpoint: Endpoint, body: object) => {
// const headers = createHeadersFn('PUT', body);
// return fetchFn(endpoint, headers);
// }
// // Function for making a DELETE request
// export const deleteFunction = (endpoint: Endpoint) => {
// const headers = createHeadersFn('DELETE', '');
// return fetchFn(endpoint, headers);
// }