Created
July 5, 2021 13:45
-
-
Save DubiousS/4d5edd26cc34b0e9d31db945ddf695ff 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 qs from 'qs'; | |
import * as humps from 'humps'; | |
import { API_URL } from '@/common/config'; | |
import tokenHelper from '@/helpers/browser/tokenHelper'; | |
const request = axios.create({ | |
baseURL: API_URL, | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
paramsSerializer: params => | |
qs.stringify(humps.decamelizeKeys(params), { | |
arrayFormat: 'brackets', | |
encodeValuesOnly: true | |
}) | |
}); | |
request.interceptors.request.use(setToken); | |
request.interceptors.request.use(requestMapper); | |
request.interceptors.response.use(saveToken); | |
request.interceptors.response.use(responseMapper, errorHandler); | |
function requestMapper(config) { | |
const newConfig = config; | |
if (newConfig.data) { | |
const decamelizedData = humps.decamelizeKeys(newConfig.data); | |
delete newConfig.data; | |
newConfig.data = decamelizedData; | |
} | |
return newConfig; | |
} | |
function responseMapper(response) { | |
return Promise.resolve( | |
humps.camelizeKeys(response.data, (key, convert) => | |
new Date(key).toString() !== 'Invalid Date' ? key : convert(key) | |
) | |
); | |
} | |
function errorHandler({ response }) { | |
const error = response | |
? { | |
message: response.data.error, | |
status: response.status | |
} | |
: {}; | |
return Promise.reject(error); | |
} | |
function saveToken(response) { | |
if (response.headers.authorization) { | |
tokenHelper.setToken(response.headers.authorization); | |
} | |
return response; | |
} | |
function setToken(config) { | |
const newConfig = config; | |
newConfig.headers.common['Authorization'] = tokenHelper.getToken(); | |
return newConfig; | |
} | |
export default request; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment