-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
84 lines (77 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* eslint-disable no-unused-vars */
/* eslint-disable no-shadow */
/* eslint-disable no-param-reassign */
/* eslint-disable no-console */
import Vue from 'vue';
import axios from 'axios';
import ApiForm from './mixins/ApiForm';
import ApiList from './mixins/ApiList';
function addInterceptors(interceptors, api) {
const {
requests: requestInterceptors,
responses: responseInterceptors,
} = interceptors;
if (requestInterceptors) {
requestInterceptors.forEach((interceptor) => {
if (Array.isArray(interceptor)) {
api.interceptors.request.use(...interceptor);
} else {
const { fulfilled, rejected } = interceptor;
api.interceptors.request.use(fulfilled, rejected);
}
});
}
if (responseInterceptors) {
responseInterceptors.forEach((interceptor) => {
if (Array.isArray(interceptor)) {
api.interceptors.response.use(...interceptor);
} else {
const { fulfilled, rejected } = interceptor;
api.interceptors.response.use(fulfilled, rejected);
}
});
}
}
const VueRest = {
install(Vue, options) {
if (Vue.vueRestInstalled) {
return;
}
Vue.vueRestInstall = true;
let api = null;
if (options && options.axiosOptions) {
api = axios.create(options.axiosOptions);
if (options.interceptors) {
addInterceptors(options.interceptors, api);
}
if (options.axiosOptions.localStorageAuthorization) {
const localStorageAuthorization =
options.axiosOptions.localStorageAuthorization;
api.interceptors.request.use((config) => {
const token = localStorage.getItem(
localStorageAuthorization.tokenItem,
);
const prefix = localStorageAuthorization.prefix;
if (!localStorageAuthorization.tokenItem || !prefix) {
console.error(
'[ERR - VueRest]: Miss configuration at localStorageAuthorization.',
);
}
if (token) {
Object.assign(config.headers, {
Authorization: `${prefix} ${token}`,
});
}
return config;
});
}
}
if (!api) {
api = axios.create();
}
Vue.api = api;
Vue.prototype.$api = api;
},
};
export { ApiList, ApiForm };
export default VueRest;