DEV Community

Ngeno Hillary
Ngeno Hillary

Posted on

My Fetch API Wrapper Function

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
epsi profile image
E.R. Nurwijayadi

Use class instead.

Collapse
 
peter_shenoda profile image
peter shenoda

Bro you should use axios.
axios use xhr and it's more compatible with old browsers than fetch