-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutilities.tsx
64 lines (58 loc) · 2.42 KB
/
utilities.tsx
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
/**
* Utility functions to make API requests.
* By importing this file, you can use the provided get and post functions.
* You shouldn't need to modify this file, but if you want to learn more
* about how these functions work, google search "Fetch API"
*
* These functions return promises, which means you should use ".then" on them.
* e.g. get('/api/foo', { bar: 0 }).then(res => console.log(res))
*/
// ex: formatParams({ some_key: "some_value", a: "b"}) => "some_key=some_value&a=b"
function formatParams(params) {
// iterate of all the keys of params as an array,
// map it to a new array of URL string encoded key,value pairs
// join all the url params using an ampersand (&).
return Object.keys(params)
.map((key) => key + "=" + encodeURIComponent(params[key]))
.join("&");
}
// convert a fetch result to a JSON object with error handling for fetch and json errors
function convertToJSON(res) {
if (!res.ok) {
throw `API request failed with response status ${res.status} and text: ${res.statusText}`;
}
return res
.clone() // clone so that the original is still readable for debugging
.json() // start converting to JSON object
.catch((error) => {
// throw an error containing the text that couldn't be converted to JSON
return res.text().then((text) => {
throw `API request's result could not be converted to a JSON object: \n${text}`;
});
});
}
// Helper code to make a get request. Default parameter of empty JSON Object for params.
// Returns a Promise to a JSON Object.
export function get(endpoint, params = {}) {
const fullPath = endpoint + "?" + formatParams(params);
return fetch(fullPath)
.then(convertToJSON)
.catch((error) => {
// give a useful error message
throw `GET request to ${fullPath} failed with error:\n${error}`;
});
}
// Helper code to make a post request. Default parameter of empty JSON Object for params.
// Returns a Promise to a JSON Object.
export function post(endpoint, params = {}) {
return fetch(endpoint, {
method: "post",
headers: { "Content-type": "application/json" },
body: JSON.stringify(params),
})
.then(convertToJSON) // convert result to JSON object
.catch((error) => {
// give a useful error message
throw `POST request to ${endpoint} failed with error:\n${error}`;
});
}