Skip to content

Commit

Permalink
Feat: Axios request interceptor + Fix: setAuthentication error on string
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastianSmolorz committed Apr 23, 2019
1 parent 2ed5dcd commit 5bff6cd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
8 changes: 6 additions & 2 deletions src/orm/axios.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ export default class Axios {
this.instance = http.axios || axios.create(http);
this.setAuthentication(http.access_token);

this.instance.interceptors.request.use(
config => http.onRequest(config, this.instance),
error => http.onError(error, this.instance),
);

this.instance.interceptors.response.use(
response => http.onResponse(response, this.instance),
error => http.onError(error, this.instance),
Expand All @@ -15,8 +20,7 @@ export default class Axios {

setAuthentication(token) {
if (!token) return;
const isFunction = typeof token
"function";
const isFunction = typeof token === 'function';
const tokenStr = isFunction ? token() : token;

this.instance.defaults.headers.common['Authorization'] = `Bearer ${tokenStr}`;
Expand Down
15 changes: 13 additions & 2 deletions src/support/interfaces.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,21 @@ export const AxiosRequestConfig = {
*/
proxy: {},

/**
* Default onRequest
* @param {object} config
* @param {Axios} Axios instance
*/
onRequest(config, axios) {
return config;
},

/**
* Default on Response
* @param {object} response
* @param {Axios} axios instance
*/
onResponse(response) {
onResponse(response, axios) {
return response.data;
},

Expand Down Expand Up @@ -134,8 +144,9 @@ export const AxiosRequestConfig = {
/**
* Default on Error
* @param {object} error
* @param {Axios} axios instance
*/
onError(error) {
onError(error, axios) {
const { response } = error;
const errorTypes = {
401: this.onUnauthorised,
Expand Down

0 comments on commit 5bff6cd

Please sign in to comment.