Skip to content

Instantly share code, notes, and snippets.

@vinayakkulkarni
Created October 15, 2018 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinayakkulkarni/5fcb4fc65099490dc2ab0d6231ab8c6e to your computer and use it in GitHub Desktop.
Save vinayakkulkarni/5fcb4fc65099490dc2ab0d6231ab8c6e to your computer and use it in GitHub Desktop.
API Middleware using axios
class Api {
constructor() {}
call(requestType, url, data = null) {
return new Promise((resolve, reject) => {
axios[requestType](url, data)
.then((response) => {
resolve(response);
})
.catch(({ response, request, message }) => {
if (response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(response.data);
// console.log(response.status);
// console.log(response.headers);
if (response.status === 401) {
// If you're using a auth middleware
// just perform logout() operation
// auth.logout();
}
} else if (request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('error.request: ', request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('error.message: ', message);
}
reject(response);
});
});
}
}
export default Api;
@vinayakkulkarni
Copy link
Author

In your main.js, register the Api class by attaching it to the window object.
something like this:

import Api from '@/middleware/api';
window.api = new Api();

In your Vuex actions or want to perform any XHRs:

getUsers({ commit }) {
  commit('usersLoading', true);
  return new Promise((resolve, reject) => {
    api.call('get', 'users')
      .then(
        (response) => {
          commit('usersLoading', false);
          commit('updateUsersData', response.data);
          resolve(response);
        },
        (error) => {
          commit('usersLoading', false);
          reject(error);
        },
      );
  });
},
updateUser({ commit }, user) {
  commit('userLoading', true);
  return new Promise((resolve, reject) => {
    api.call('patch', `users/${user.id}`, user)
      .then(
        (response) => {
          commit('userLoading', false);
          commit('updateUserData', response.data);
          resolve(response);
        },
        (error) => {
          commit('userLoading', false);
          reject(error);
        },
      );
  });
},

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment