-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
124 lines (117 loc) · 2.8 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import axios from 'axios'
export const withHttpCalls = ({
baseURL = '/api',
httpCalls = [],
state = {},
actions = {},
mutations = {},
getters = {},
namespaced = true
}) => {
const api = axios.create({
baseURL
})
api.interceptors.request.use(
async conf => {
try {
state.requesting = true
return {
...conf,
...(state.token === ''
? {}
: {
headers: {
...conf.header,
Authorization: `Bearer ${state.token}`
}
})
}
} catch (error) {
state.requesting = false
}
},
error => {
state.requesting = false
return Promise.reject(error)
}
)
api.interceptors.response.use(
response => {
state.requesting = false
return response
},
error => {
state.requesting = false
return Promise.reject(error)
}
)
state = {
...state,
requesting: false,
token: ''
}
mutations = {
...mutations,
setToken(state, { token }) {
state.token = token
},
set(state, { key, value }) {
state[key] = value
}
}
actions = httpCalls.reduce(
(obj, def) =>
Object.defineProperty(obj, `${def.name ? def.name : def.url}`, {
enumerable: true,
configurable: true,
value: async function({ commit }, actionArgs) {
try {
let requestPayload = {
data: actionArgs,
url: def.url,
method: `${def.method ? def.method : 'get'}`
}
const { data } = await api.request(requestPayload)
// track result in store if required
if (def.resultToStateField) {
commit('set', { key: def.resultToStateField, value: data })
}
// if we need to do something with the result
if (def.onSuccess) {
def.onSuccess(data)
}
return data
} catch (e) {
// if we need to do something with the result
if (def.onError && typeof def.onError === 'function') {
def.onError(e)
}
// if we need to do something on specific error status
if (
e.response &&
e.response.status &&
typeof def.onError === 'object' &&
def.onError[e.response.status] &&
typeof def.onError[e.response.status] === 'function'
) {
def.onError[e.response.status](e)
}
}
}
}),
{
...actions,
setToken({ commit }, { token }) {
commit('setToken', { token })
}
}
)
// return the vuex module
return {
namespaced,
state,
getters,
mutations,
actions
}
}