After learning higher-order functions in Javascript, I decided to write this Fetch API wrapper function.
export const http = (method=`GET`, data={},) => {
const baseURL = `http://localhost:8000/api/v1`;
const headers = {
'Content-Type': 'application/json;charset=utf-8',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
'X-Requested-With': 'XMLHttpRequest',
};
const body = JSON.stringify({
...data,
});
switch (method) {
case `GET`:
return (url) => fetch(`${baseURL}/${url}`, { method, headers,})
.then(response => {
if(parseInt(response.status) > 300) {
return response.json().then(resp => {
return Promise.reject(resp);
});
}
return response.json().then(resp => {
return Promise.resolve(resp);
});
});
case `POST`:
return (url) =>fetch(`${baseURL}/${url}`, {method, headers, body,})
.then(response => {
if(parseInt(response.status) > 300) {
return response.json().then(resp => {
return Promise.reject(resp);
});
}
return response.json().then(resp => {
return Promise.resolve(resp);
});
});
case `DELETE`:
return (url) => fetch(`${baseURL}/${url}`, {method, headers, body,})
.then(response => {
if(parseInt(response.status) > 300) {
return response.json().then(resp => {
return Promise.reject(resp);
});
}
return response.json().then(resp => {
return Promise.resolve(resp);
});
});
case `PUT`:
return (url) => fetch(`${baseURL}/${url}`, {method, headers, body,})
.then(response => {
if(parseInt(response.status) > 300) {
return response.json().then(resp => {
return Promise.reject(resp);
});
}
return response.json().then(resp => {
return Promise.resolve(resp);
});
});
default:
break;
}
}
How I implement it on my application:
import {http} from './http';
http('POST', { name: "ngeno7"})('user-endpoint').then(response => {
console.log("data", response);
}).catch(error => {
console.log("error", error);
});
Top comments (2)
Bro you should use axios.
axios use xhr and it's more compatible with old browsers than fetch
Use class instead.