From 5bff6cd83054807dd3e014068ff52db026ac4a9c Mon Sep 17 00:00:00 2001 From: seb Date: Tue, 23 Apr 2019 22:58:10 +0100 Subject: [PATCH] Feat: Axios request interceptor + Fix: setAuthentication error on string --- src/orm/axios.js | 8 ++++++-- src/support/interfaces.js | 15 +++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/orm/axios.js b/src/orm/axios.js index d0aeed4..d7174ca 100644 --- a/src/orm/axios.js +++ b/src/orm/axios.js @@ -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), @@ -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}`; diff --git a/src/support/interfaces.js b/src/support/interfaces.js index 0aa8267..545e1a6 100644 --- a/src/support/interfaces.js +++ b/src/support/interfaces.js @@ -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; }, @@ -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,