1
- import { host , restApiRoot , port } from '~/server/config.json' ;
1
+ import { host , restApiRoot , port } from '~/server/config.json' ;
2
2
import axios from 'axios' ;
3
3
4
4
const Storage = window . localStorage ;
@@ -30,6 +30,15 @@ const http = axios.create({
30
30
baseURL : `http://${ host } :${ port } ${ restApiRoot } ` ,
31
31
} ) ;
32
32
33
+ // Current setLoading function
34
+ let setLoading = ( ) => {
35
+ throw Error ( 'setLoadingFunction not defined' ) ;
36
+ } ;
37
+
38
+ http . setLoadingFunction = ( fn ) => {
39
+ setLoading = fn ;
40
+ } ;
41
+
33
42
http . setToken = ( token , save = true ) => {
34
43
http . token = token ;
35
44
http . defaults . headers . common . Authorization = token . id ;
@@ -41,9 +50,10 @@ http.removeToken = () => {
41
50
removeTokenFromLocalStorage ( ) ;
42
51
} ;
43
52
44
- http . find = ( endpoint , filter ) => http . get ( endpoint , { params : { filter} } ) ;
53
+ http . find = ( endpoint , filter ) => http . get ( endpoint , { params : { filter } } ) ;
45
54
46
- const interceptErrors = ( err ) => {
55
+ /* Response Interceptors */
56
+ const interceptResErrors = ( err ) => {
47
57
try {
48
58
err = Object . assign ( new Error ( ) , err . response . data . error ) ;
49
59
} catch ( e ) {
@@ -52,17 +62,28 @@ const interceptErrors = (err) => {
52
62
return Promise . reject ( err ) ;
53
63
} ;
54
64
const interceptResponse = ( res ) => {
65
+ // console.log('response', res.config);
66
+ setLoading ( false , res . config . uid ) ;
55
67
try {
56
68
return res . data ;
57
69
} catch ( e ) {
58
70
return res ;
59
71
}
60
72
} ;
61
- http . interceptors . response . use ( interceptResponse , interceptErrors ) ;
73
+ http . interceptors . response . use ( interceptResponse , interceptResErrors ) ;
62
74
63
75
// Set storage Token in http if exists
64
76
addTokenFromLocalStorage ( http ) ;
65
77
78
+ /* Request Interceptors */
79
+ const interceptReqErrors = err => Promise . reject ( err ) ;
80
+ const interceptRequest = ( config ) => {
81
+ config . uid = setLoading ( true ) ;
82
+ // console.log('request', config);
83
+ return config ;
84
+ } ;
85
+ http . interceptors . request . use ( interceptRequest , interceptReqErrors ) ;
86
+
66
87
export default http ;
67
88
68
89
// Documentation: https://github.com/axios/axios
0 commit comments