Created
September 25, 2018 04:37
-
-
Save 6temes/e76d57765a42de5cbfee867753e967a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
import jsifyKeysDeep from 'jsify-case-keys-deep' // Like `camelcase-keys-deep` but also transforms suffix '?' with prefix `is` | |
import decamelizeKeysDeep from 'decamelize-keys-deep' | |
import Qs from 'qs' | |
export default (baseURL) => { | |
const axiosClient = axios.create({ | |
baseURL, | |
responseType: 'json', | |
}) | |
axiosClient.interceptors.response.use( | |
(response) => { | |
// Reload if a new backend has been deployed but the user is still using an | |
// old version of the React app | |
const apiVersion = response.headers['x-api-version'] | |
const localVersion = global.window.REACT_API_RELEASE_VERSION | |
if (localVersion !== apiVersion) global.location.reload() | |
return jsifyKeysDeep(response) | |
}, | |
(error) => { | |
// Reload if unauthorized. After reload, Devise will kick in and redirect | |
// to the login page. | |
if (error.response && error.response.status === 401) global.location.reload() | |
return Promise.reject(error) | |
}, | |
) | |
axiosClient.interceptors.request.use( | |
config => (config.data instanceof global.FormData | |
? config | |
: { | |
...config, | |
data: decamelizeKeysDeep(config.data), | |
params: decamelizeKeysDeep(config.params), | |
paramsSerializer: params => Qs.stringify(params, { | |
arrayFormat: 'brackets', | |
encode: false, | |
}), | |
}), | |
error => Promise.reject(error), | |
) | |
const csrfMetaTag = global.document.getElementsByName('csrf-token')[0] | |
// csrf-token is not rendred in tests | |
if (csrfMetaTag) { | |
axiosClient.defaults.headers.common['X-CSRF-Token'] = csrfMetaTag.content | |
} | |
return axiosClient | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you, 🤦♂️ that's much cleaner, I totally missed the obvious answer!
I've been considering axios middleware with redux - thanks for the config integration on that, I'll check that out when I get around to moving that direction.