-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathleancloud.js
194 lines (178 loc) · 5.75 KB
/
leancloud.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/* global CONFIG */
(function(window, document) {
// 查询存储的记录
function getRecord(Counter, target) {
return new Promise(function(resolve, reject) {
Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ target })))
.then(resp => resp.json())
.then(({ results, code, error }) => {
if (code === 401) {
throw error;
}
if (results && results.length > 0) {
var record = results[0];
resolve(record);
} else {
Counter('post', '/classes/Counter', { target, time: 0 })
.then(resp => resp.json())
.then((record, error) => {
if (error) {
throw error;
}
resolve(record);
}).catch(error => {
// eslint-disable-next-line no-console
console.error('Failed to create', error);
reject(error);
});
}
}).catch((error) => {
// eslint-disable-next-line no-console
console.error('LeanCloud Counter Error:', error);
reject(error);
});
});
}
// 发起自增请求
function increment(Counter, incrArr) {
return new Promise(function(resolve, reject) {
Counter('post', '/batch', {
'requests': incrArr
}).then((res) => {
res = res.json();
if (res.error) {
throw res.error;
}
resolve(res);
}).catch((error) => {
// eslint-disable-next-line no-console
console.error('Failed to save visitor count', error);
reject(error);
});
});
}
// 构建自增请求体
function buildIncrement(objectId) {
return {
'method': 'PUT',
'path' : `/1.1/classes/Counter/${objectId}`,
'body' : {
'time': {
'__op' : 'Increment',
'amount': 1
}
}
};
}
// 校验是否为有效的 Host
function validHost() {
if (CONFIG.web_analytics.leancloud.ignore_local) {
var hostname = window.location.hostname;
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return false;
}
}
return true;
}
// 校验是否为有效的 UV
function validUV() {
var key = 'LeanCloud_UV_Flag';
var flag = localStorage.getItem(key);
if (flag) {
// 距离标记小于 24 小时则不计为 UV
if (new Date().getTime() - parseInt(flag, 10) <= 86400000) {
return false;
}
}
localStorage.setItem(key, new Date().getTime().toString());
return true;
}
function addCount(Counter) {
var enableIncr = CONFIG.web_analytics.enable && validHost();
var getterArr = [];
var incrArr = [];
// 请求 PV 并自增
var pvCtn = document.querySelector('#leancloud-site-pv-container');
if (pvCtn) {
var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
enableIncr && incrArr.push(buildIncrement(record.objectId));
var ele = document.querySelector('#leancloud-site-pv');
if (ele) {
ele.innerText = (record.time || 0) + (enableIncr ? 1 : 0);
pvCtn.style.display = 'inline';
}
});
getterArr.push(pvGetter);
}
// 请求 UV 并自增
var uvCtn = document.querySelector('#leancloud-site-uv-container');
if (uvCtn) {
var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
var incrUV = validUV() && enableIncr;
incrUV && incrArr.push(buildIncrement(record.objectId));
var ele = document.querySelector('#leancloud-site-uv');
if (ele) {
ele.innerText = (record.time || 0) + (incrUV ? 1 : 0);
uvCtn.style.display = 'inline';
}
});
getterArr.push(uvGetter);
}
// 如果有页面浏览数节点,则请求浏览数并自增
var viewCtn = document.querySelector('#leancloud-page-views-container');
if (viewCtn) {
var path = eval(CONFIG.web_analytics.leancloud.path || 'window.location.pathname');
var target = decodeURI(path.replace(/\/*(index.html)?$/, '/'));
var viewGetter = getRecord(Counter, target).then((record) => {
enableIncr && incrArr.push(buildIncrement(record.objectId));
var ele = document.querySelector('#leancloud-page-views');
if (ele) {
ele.innerText = (record.time || 0) + (enableIncr ? 1 : 0);
viewCtn.style.display = 'inline';
}
});
getterArr.push(viewGetter);
}
// 如果启动计数自增,批量发起自增请求
if (enableIncr) {
Promise.all(getterArr).then(() => {
incrArr.length > 0 && increment(Counter, incrArr);
});
}
}
var appId = CONFIG.web_analytics.leancloud.app_id;
var appKey = CONFIG.web_analytics.leancloud.app_key;
var serverUrl = CONFIG.web_analytics.leancloud.server_url;
if (!appId) {
throw new Error('LeanCloud appId is empty');
}
if (!appKey) {
throw new Error('LeanCloud appKey is empty');
}
function fetchData(api_server) {
var Counter = (method, url, data) => {
return fetch(`${api_server}/1.1${url}`, {
method,
headers: {
'X-LC-Id' : appId,
'X-LC-Key' : appKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
};
addCount(Counter);
}
var apiServer = appId.slice(-9) !== '-MdYXbMMI' ? serverUrl : `https://${appId.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;
if (apiServer) {
fetchData(apiServer);
} else {
fetch('https://app-router.leancloud.cn/2/route?appId=' + appId)
.then(resp => resp.json())
.then((data) => {
if (data.api_server) {
fetchData('https://' + data.api_server);
}
});
}
})(window, document);