Created
February 1, 2017 10:15
-
-
Save rgommezz/cc9d999b8a52302f2b4608dd0f248aba to your computer and use it in GitHub Desktop.
This file contains 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 LocalStorage from '../logic/LocalStorage'; | |
let instance; | |
const ACCEPT_HEADER = 'application/json, text/plain, */*; api-token:'; | |
const CONTENT_TYPE_HEADER = 'application/x-www-form-urlencoded'; | |
const defaultHeaders = { | |
Accept: ACCEPT_HEADER, | |
'Content-Type': CONTENT_TYPE_HEADER, | |
}; | |
/** | |
* Gets the axios instance | |
*/ | |
export const getInstance = () => instance; | |
/** | |
* Set the token header after logging in | |
* @param AUTH_TOKEN | |
*/ | |
export const setTokenHeader = (AUTH_TOKEN) => { | |
instance.defaults.headers.Accept = `${ACCEPT_HEADER}${AUTH_TOKEN}`; | |
}; | |
/** | |
* Remove token header after logging out | |
*/ | |
export const removeTokenHeader = () => { | |
instance.defaults.headers.Accept = defaultHeaders.Accept; | |
}; | |
/** | |
* Create a new instance of axios with the provided config | |
* @param baseURL, client API endpoint | |
*/ | |
export function createRestInstance(baseURL) { | |
instance = axios.create({ | |
baseURL, | |
headers: defaultHeaders, | |
}); | |
} | |
/** | |
* Check token in localStorage, in case user was previously logged in | |
*/ | |
export function checkIfUserWasLoggedIn() { | |
const stashedData = LocalStorage.getData(); | |
if (stashedData.token) { | |
setTokenHeader(stashedData.token); | |
} | |
} | |
export const rest = { | |
httpGet: url => instance.get(url), | |
httpPost: (url, payload) => instance.post(url, payload), | |
httpDelete: url => instance.delete(url), | |
httpPut: (url, payload) => instance.put(url, payload), | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment