create-api-client.js
2.9 KB
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
import axios from 'axios';
import {get} from 'lodash';
import yoho from './yoho';
import sdk from 'common/sdk';
import qs from 'yoho-qs';
const protocol = location.protocol === 'yoho-protocol:' ? 'http:' : location.protocol;
axios.defaults.baseURL = `${protocol}//${location.host}/grass`;
axios.defaults.responseType = 'json';
axios.defaults.headers = {
'X-Requested-With': 'XMLHttpRequest'
};
const errHandle = (error) => {
let res = error.response;
console.log(error);
if (+res.status === 510) {
if (get(res, 'data.data.refer')) {
return window.location.href === get(res, 'data.data.refer');
}
}
return Promise.reject({
code: 500,
message: '服务器开小差了~'
});
};
const getUser = async(store) => {
let {appUid, appSessionKey, appVersion, appClientType} = store.state.yoho.user;
try {
if (!appUid || !appSessionKey || !appVersion || !appClientType) {
const {uid, session_key, app_version, client_type} = qs;
if (uid && app_version && client_type) {
appUid = +uid;
appSessionKey = session_key;
appVersion = app_version;
appClientType = client_type;
store.commit('SET_USER', {appUid, appSessionKey, appVersion, appClientType});
if (!appUid || !appSessionKey) {
sdk.getUser().then(user => { // 页面第一次进入时,app未登录情况下,有一定几率没有回调,所以异步更新
if (user) {
store.commit('SET_USER', {
appUid: +user.uid,
appSessionKey: user.sessionKey,
appVersion: user.appVersion,
appClientType: user.sessionType
});
}
});
}
}
}
} catch (e) {
store.dispatch('reportError', {error: e});
}
return {appUid, appSessionKey, appVersion, appClientType};
};
const request = async(options, store) => {
if (yoho.isLocal && yoho.isApp) {
options.headers = {
'yoho-protocol': true
};
let {appUid, appSessionKey, appVersion, appClientType} = await getUser(store);
if (appUid && appSessionKey && appVersion && appClientType) {
options.headers['app-uid'] = appUid;
options.headers['app-session-key'] = appSessionKey;
options.headers['app-version'] = appVersion;
options.headers['app-client-type'] = appClientType;
}
}
return axios(options).then((res) => {
if (res.data.code === 401) {
store && store.commit('SET_NEED_LOGIN', {needLogin: true});
return Promise.reject(res.data);
}
return res.data;
}, errHandle);
};
export const createApi = (context, store) => {
return {
get(url, params, options) {
return request(Object.assign({
url,
params,
method: 'get',
}, options), store);
},
post(url, data, options) {
return request(Object.assign({
url,
data,
method: 'post',
}, options), store);
}
};
};