-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.js
More file actions
27 lines (25 loc) · 1.06 KB
/
API.js
File metadata and controls
27 lines (25 loc) · 1.06 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
export const API = {};
API.get = (endpoint) => callFetch(endpoint, 'GET', null);
API.post = (endpoint, data) => callFetch(endpoint, 'POST', data);
API.put = (endpoint, data) => callFetch(endpoint, 'PUT', data);
API.delete = (endpoint) => callFetch(endpoint, 'DELETE', null);
export const callFetch = async (endpoint, method, dataObj) => {
let requestObj = { method: method };
if (dataObj) requestObj = {
...requestObj,
headers: { 'Content-type': 'application/json' },
body: JSON.stringify(dataObj)
}
try {
let responseBody = null;
const response = await fetch(endpoint, requestObj);
if (response.status !== 204) responseBody = await response.json();
return (response.status >= 100) && (response.status <= 599)
? { success: true, response: response, responseBody: responseBody }
: { success: false, response: response }
}
catch (error) {
return { success: false, response: new Response(error.message, { status: 400, statusText: "Bad Request" }) };
}
}
export default API;