Skip to content

Instantly share code, notes, and snippets.

@IAmRC1
Created August 4, 2021 13:49
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 IAmRC1/3c6ffeeb394b6c53d4e69eab31df8a01 to your computer and use it in GitHub Desktop.
Save IAmRC1/3c6ffeeb394b6c53d4e69eab31df8a01 to your computer and use it in GitHub Desktop.
Axios-DRY
const baseURL = 'https://gorest.co.in/public-api'
const token = 'jwt-token'
const apiConfig = (url, method = 'get', isTokenIncluded = false, params = {}, data = {}) => {
if(isTokenIncluded){
return {
url,
method,
baseURL,
headers: {
'Authorization': `Bearer ${token}`
},
params,
data,
}
}
return {
url,
method,
baseURL,
params,
data,
}
}
export default apiConfig;
import axios from 'axios'
import apiConfig from './apiConfig'
import { customToast } from './customToast'
const handleApi = async (url, method, isTokenIncluded, params, data) => {
try {
const response = await axios.request(apiConfig(url, method, isTokenIncluded, params, data))
return response.data;
} catch (error) {
if (error.response) {
const { status } = error.response
switch (status) {
case 500:
return customToast('Internal Server Error', 'error')
case 501:
return customToast('Not Implemented', 'error')
case 502:
return customToast('Bad Gateway', 'error')
case 503:
return customToast('Service Unavailable', 'error')
case 504:
return customToast('Gateway Timeout', 'error')
case 505:
return customToast('HTTP Version Not Supported', 'error')
case 506:
return customToast('Variant Also Negotiates', 'error')
case 507:
return customToast('Insufficient Storage', 'error')
case 508:
return customToast('Loop Detected', 'error')
case 510:
return customToast('Not Extended', 'error')
case 511:
return customToast('Network Authentication Required', 'error')
case 599:
return customToast('Network Connect Timeout Error', 'error')
default:
break;
}
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(`error.response.data`, error.response.data)
// console.log(`error.response.status`, error.response.status)
// console.log(`error.response.headers`, error.response.headers)
} else if (error.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`, error.request)
return customToast('Server Not Responding', 'error');
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error Message', error.message);
}
// console.log(`error.config`, error.config)
}
}
export default handleApi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment