Created
May 25, 2018 12:57
-
-
Save gogumai/5dc7fdb827d7a9dcaf26063049938001 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 humps from 'humps' | |
| import Config from 'react-native-config' | |
| import { store } from '../store' | |
| import { setUserSession, signOut } from '../actions/auth' | |
| const API_URL = Config.API_URL | |
| const createAxiosClient = () => { | |
| const userSession = store.getState().auth.userSession | |
| let headers = { } | |
| if (userSession) { | |
| const { token, client, uid } = userSession | |
| headers = { | |
| 'Access-Token': token, | |
| 'Client': client, | |
| 'Uid': uid | |
| } | |
| } | |
| const client = axios.create({ | |
| baseURL: API_URL, | |
| headers, | |
| transformRequest: [ | |
| data => humps.decamelizeKeys(data), | |
| ...axios.defaults.transformRequest | |
| ], | |
| transformResponse: [ | |
| ...axios.defaults.transformResponse, | |
| data => humps.camelizeKeys(data) | |
| ] | |
| }) | |
| client.interceptors.response.use( | |
| response => { | |
| const { headers } = response | |
| const token = headers['access-token'] | |
| const client = headers['client'] | |
| const uid = headers['uid'] | |
| if (token && client && uid) { | |
| store.dispatch(setUserSession({ token, client, uid })) | |
| } | |
| return response | |
| }, | |
| error => { | |
| if (error.request.status === 401 && userSession) { | |
| return store.dispatch(signOut()) | |
| } | |
| return Promise.reject(error) | |
| } | |
| ) | |
| return client | |
| } | |
| export default createAxiosClient |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment