mirror of
https://github.com/mudabbir-ahmad/Project-MAD-crudler.git
synced 2026-10-07 20:40:20 +00:00
week5 act 1
This commit is contained in:
1 parent
967c9342e1
commit
aa51aae32f
2 files changed
+49
-6
No files matched your search
@@ -0,0 +1,31 @@
|
||||
const API = {};
|
||||
|
||||
API.get = (endpoint) => callFetch(endpoint, 'GET');
|
||||
API.post = (endpoint, data) => callFetch(endpoint, 'POST', data);
|
||||
API.put = (endpoint, data) => callFetch(endpoint, 'PUT', data);
|
||||
API.delete = (endpoint) => callFetch(endpoint, 'DELETE');
|
||||
|
||||
export default API;
|
||||
|
||||
const callFetch = async (endpoint, method, dataObj = null) => {
|
||||
// Build request object
|
||||
let requestObj = {method: method}; // GET, POST, PUT or DELETE
|
||||
if (dataObj)
|
||||
requestObj = {
|
||||
...requestObj,
|
||||
headers: {'Content-type': 'application/json'},
|
||||
body: JSON.stringify(dataObj),
|
||||
};
|
||||
|
||||
// Call the fetch and process the return
|
||||
try {
|
||||
let result = null;
|
||||
const response = await fetch(endpoint, requestObj);
|
||||
if (response.status !== 204) result = await response.json();
|
||||
return response.status >= 200 && response.status < 300
|
||||
? {isSuccess: true, result}
|
||||
: {isSuccess: false, message: `${result.message}`};
|
||||
} catch (error) {
|
||||
return {isSuccess: false, message: error.message};
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user