Skip to content

Instantly share code, notes, and snippets.

@matthewblewitt
Created January 29, 2020 16:14
Show Gist options
  • Save matthewblewitt/f555d83c568c06e866df5278e84295e7 to your computer and use it in GitHub Desktop.
Save matthewblewitt/f555d83c568c06e866df5278e84295e7 to your computer and use it in GitHub Desktop.
// Axios.prototype cannot be modified
const axiosExtra = {
setBaseURL (baseURL) {
this.defaults.baseURL = baseURL
},
setHeader (name, value, scopes = 'common') {
for (let scope of Array.isArray(scopes) ? scopes : [ scopes ]) {
if (!value) {
delete this.defaults.headers[scope][name];
return
}
this.defaults.headers[scope][name] = value
}
},
setToken (token, type, scopes = 'common') {
const value = !token ? null : (type ? type + ' ' : '') + token
this.setHeader('Authorization', value, scopes)
},
onRequest(fn) {
this.interceptors.request.use(config => fn(config) || config)
},
onResponse(fn) {
this.interceptors.response.use(response => fn(response) || response)
},
onRequestError(fn) {
this.interceptors.request.use(undefined, error => fn(error) || Promise.reject(error))
},
onResponseError(fn) {
this.interceptors.response.use(undefined, error => fn(error) || Promise.reject(error))
},
onError(fn) {
this.onRequestError(fn)
this.onResponseError(fn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment