-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
54 lines (47 loc) · 1.32 KB
/
request.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
import axios from 'axios';
import genv from './env';
const serverHost = /(\.[-\w]+\.[-\w]+)$/.exec(window.location.hostname)[1];
export async function request({
method = 'get',
scope,
url,
params,
data,
env
}) {
if (!url.startsWith('http')) {
url = `${getHost(scope, { env })}/api/${url}`;
}
if (method === 'get') {
params = { ...params, ...data, _: Date.now() };
}
const res = await axios({
method,
url,
params,
data,
withCredentials: true
});
return res.data;
}
export async function get(scope, url, params, opts) {
const res = await request({ scope, url, params, method: 'get', ...opts });
return res.isSuccess && res.data;
}
export async function post(scope, url, data, opts) {
const res = await request({ scope, url, data, method: 'post', ...opts });
return res.isSuccess;
}
export function postSync(scope, url, data) {
const xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', `${getHost(scope)}/api/${url}`, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xmlhttp.send(JSON.stringify(data));
}
function getHost(scope, opts = {}) {
const env = opts.env || genv;
return env === 'development' ?
`https://${scope}.dev${serverHost}` :
`https://${scope}${serverHost}`;
}
export default { request, get, post, postSync };