Created
September 27, 2019 00:29
-
-
Save 6temes/45c30c88d471d1c483dc1207b099e5a4 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 Qs from 'qs' | |
import axios from 'axios' | |
import axiosMiddleware from 'redux-axios-middleware' | |
import decamelizeKeysDeep from 'decamelize-keys-deep' | |
import jsifyKeysDeep from 'jsify-case-keys-deep' // Like `camelcase-keys-deep` but also transforms suffix '?' with prefix `is` | |
const axiosMiddlewareConfig = { | |
interceptors: { | |
request: [ | |
(_, request) => { | |
if (request.data instanceof global.FormData) return request | |
return { | |
...request, | |
data: decamelizeKeysDeep(request.data), | |
params: decamelizeKeysDeep(request.params), | |
paramsSerializer: params => | |
Qs.stringify(params, { | |
arrayFormat: 'brackets', | |
encode: false, | |
}), | |
} | |
}, | |
], | |
response: [ | |
{ | |
success: (_, response) => { | |
// Reload if a new backend has been deployed but the user is still using an | |
// old version of the React app | |
const toNumber = str => +str.replace(/\D/g, '') | |
const compatibleVersion = toNumber(response.headers['x-api-version-compatible']) | |
const localVersion = toNumber(global.window.RELEASE_VERSION) | |
if (localVersion && compatibleVersion && localVersion < compatibleVersion) { | |
console.warn('Using an old version of the App. Reloading to get the latest changes...') /* eslint-disable-line */ | |
console.warn(`Local version: ${localVersion}`) /* eslint-disable-line */ | |
console.warn(`..... ${global.window.RELEASE_VERSION}`) /* eslint-disable-line */ | |
console.warn(`Last compatible version: ${compatibleVersion}`) /* eslint-disable-line */ | |
console.warn(`..... ${response.headers['x-api-version-compatible']}`) /* eslint-disable-line */ | |
setTimeout(global.location.reload(), 1000) | |
} | |
return jsifyKeysDeep(response) | |
}, | |
error: ({ dispatch }, error) => { | |
if (error.response && error.response.statusText === 'Unauthorized') { | |
dispatch({ | |
type: '@@axios-api/UNAUTHORIZED_REQUEST', | |
errors: jsifyKeysDeep(error.response.data), | |
}) | |
} | |
if (error.response && error.response.statusText === 'Service Unavailable') { | |
// eslint-disable-next-line | |
console.warn('App is in maintenance mode. Reloading...') | |
setTimeout(global.location.reload(), 2000) | |
} | |
return Promise.reject(jsifyKeysDeep(error)) | |
}, | |
}, | |
], | |
}, | |
} | |
export const createAxiosMiddleware = ({ baseURL }) => { | |
const axiosClient = axios.create({ | |
baseURL, | |
responseType: 'json', | |
}) | |
return axiosMiddleware(axiosClient, axiosMiddlewareConfig) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment