Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Axios request interceptor + Fix: setAuthentication error on string #45

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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