-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
100 lines (73 loc) · 2.17 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
import _ from 'lodash';
import axios from 'axios';
export default class ApiService {
constructor(config = {}) {
this.token = config.token;
this.unauthenticated = config.unauthenticated;
this.maxDepth = config.maxDepth;
this.axios = axios.create({
...config,
});
this.axios.interceptors.response.use(null, async (error) => {
if (error.response && error.response.status === 401) {
const unauthenticated = this.unauthenticated || window.app.auth.unauthenticated || null;
if (unauthenticated) {
return unauthenticated();
} else {
return Promise.reject(error);
}
} else {
return Promise.reject(error);
}
});
}
async request(config = {}) {
const {headers, ...rest} = config;
const baseUrl = config.apiBaseUrl || window.app.env.apiBaseUrl || '';
let token = null;
if (this.token) {
token = this.token();
} else if (window.app.auth.getToken) {
token = await window.app.auth.getToken();
}
const requestHeaders = {
Authorization: token ? `Bearer ${token}` : null,
...headers,
};
return this.axios({
headers: requestHeaders,
baseURL: baseUrl || '',
responseType: 'json',
...rest,
});
}
prepareParams(params) {
if (params && Array.isArray(params.include)) {
params.include = params.include.join(',');
}
if (params && Array.isArray(params.require)) {
params.require = params.require.join(',');
}
return params;
}
preparePayload(data, currentDepth = 0) {
const maxDepth = this.maxDepth || window.app.env.apiMaxDepth || 3;
if (currentDepth >= maxDepth) {
return data;
}
if (Array.isArray(data)) {
return data.map(item => this.preparePayload(item, currentDepth + 1));
} else if (typeof data === 'string' || data === null) {
return data;
} else if (typeof data === 'object') {
let snaked = {};
for (let key in data) {
if (data.hasOwnProperty(key)) {
snaked[_.snakeCase(key)] = this.preparePayload(data[key], currentDepth + 1);
}
}
return snaked;
}
return data;
}
}