-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstatus.js
More file actions
168 lines (139 loc) · 4.4 KB
/
Copy pathstatus.js
File metadata and controls
168 lines (139 loc) · 4.4 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
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
// ref: https://blog.zhheo.com/p/61e9.html
// 配置参数
const CONFIG = {
API_BASE_URL: 'https://umami-status-api.domain.com',
USERNAME: 'umami user',
PASSWORD: 'change this password',
WEBSITE_ID: 'your umami website id',
CACHE_TIME: 600 // 缓存时间10分钟(单位:秒)
}
const corsHeaders = {
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
'Access-Control-Max-Age': '600',
'Content-Type': 'application/json',
'Cache-Control': 'private, max-age=600',
};
// 设置CORS头
const headers = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
const CACHE_DATA = new Map();
const CACHE_DURATION = 10 * 60 * 1000; // 10 min
// 获取Token的辅助函数
async function getToken() {
const url = `${CONFIG.API_BASE_URL}/api/auth/login`
let tokenResponse = CACHE_DATA.get('token')
if (tokenResponse) {
return tokenResponse
}
// 如果缓存中没有Token,则请求获取
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: CONFIG.USERNAME,
password: CONFIG.PASSWORD
})
})
if (!response.ok) {
throw new Error(`Failed to login! status: ${response.status}`)
}
const data = await response.json()
const token = data.token
CACHE_DATA.set('token', data.token)
return token
}
// 处理请求的主函数
async function handleRequest(request) {
//console.log(CACHE_DATA)
if (request.method === "OPTIONS") {
return new Response("OK", {
headers: corsHeaders
});
}
// 检查缓存是否存在且未过期
let cachedData = CACHE_DATA.get('data');
let cachedTimestamp = CACHE_DATA.get('ts');
const now = Date.now();
if (cachedData && cachedTimestamp && (now - cachedTimestamp < CACHE_DURATION)) {
console.log('data cache')
// 返回缓存的数据
return new Response(JSON.stringify(cachedData), {
headers: {
...corsHeaders,
}
});
}
// 获取Token
const token = await getToken()
if (!token) {
return new Response(JSON.stringify({ error: 'Failed to obtain token' }), {
status: 500,
...corsHeaders
})
}
// 获取当前时间戳(毫秒)
const currentTimestamp = now
// 计算各个时间段的起始时间戳
const startTimestampToday = new Date().setHours(0, 0, 0, 0)
const startTimestampYesterday = startTimestampToday - 86400000
const startTimestampLastMonth = currentTimestamp - 30 * 86400000
const startTimestampLastYear = currentTimestamp - 365 * 86400000
// 如果没有缓存,则获取新数据
try {
const [todayData, yesterdayData, lastMonthData, lastYearData] = await Promise.all([
fetchUmamiData(startTimestampToday, currentTimestamp, token),
fetchUmamiData(startTimestampYesterday, startTimestampToday, token),
fetchUmamiData(startTimestampLastMonth, currentTimestamp, token),
fetchUmamiData(startTimestampLastYear, currentTimestamp, token)
])
const responseData = {
today_uv: todayData?.visitors?.value,
today_pv: todayData?.pageviews?.value,
yesterday_uv: yesterdayData?.visitors?.value,
yesterday_pv: yesterdayData?.pageviews?.value,
last_month_pv: lastMonthData?.pageviews?.value,
last_year_pv: lastYearData?.pageviews?.value
}
// 更新缓存
CACHE_DATA.set('ts', currentTimestamp);
CACHE_DATA.set('data', responseData);
//console.log('data got')
//console.log(CACHE_DATA)
// 创建响应并缓存
response = new Response(JSON.stringify(responseData), {
headers: {
...corsHeaders
}
})
return response
} catch (error) {
return new Response(JSON.stringify({ error: 'Failed to fetch data' }), {
status: 500,
...corsHeaders
})
}
}
// 获取Umami数据的辅助函数
async function fetchUmamiData(startAt, endAt, token) {
const url = `${CONFIG.API_BASE_URL}/api/websites/${CONFIG.WEBSITE_ID}/stats?startAt=${startAt}&endAt=${endAt}`
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return await response.json()
}
// 注册Worker
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})