CF Worker部署Umami的API

感谢@spark 提供的worker脚本,感谢张洪Heo提供的获取Token方法

前因

准备食用

食用前需要烹饪一番

首先进入Hoppscotch 获取token

成功后会返回token信息

装盘

  1. 直接去cloudflare创建一个Workers,修改名称点击部署
  2. 部署完后在右上角点击编辑代码修改worker.js的内容
  3. 粘贴下面的内容,并修改 API_BASE_URLTOKENWEBSITE_ID为你的内容

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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event));
});

const API_BASE_URL = 'https://umami.yourdomain.com';
const TOKEN = 'your_token';
const WEBSITE_ID = 'your_website_id';
const CACHE_KEY = 'umami_cache';
const CACHE_TIME = 600; // Cache time in seconds

async function fetchUmamiData(startAt, endAt) {
const url = `${API_BASE_URL}/api/websites/${WEBSITE_ID}/stats?startAt=${startAt}&endAt=${endAt}`;
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${TOKEN}`,
'Content-Type': 'application/json'
}
});

if (!response.ok) {
console.error(`Error fetching data: ${response.statusText}`);
return null;
}

return response.json();
}

async function handleRequest(event) {
const cache = await caches.open(CACHE_KEY);
const cachedResponse = await cache.match(event.request);

if (cachedResponse) {
return cachedResponse;
}

const now = Date.now();
const todayStart = new Date(now).setHours(0, 0, 0, 0);
const yesterdayStart = new Date(now - 86400000).setHours(0, 0, 0, 0);
const lastMonthStart = new Date(now).setMonth(new Date(now).getMonth() - 1);
const lastYearStart = new Date(now).setFullYear(new Date(now).getFullYear() - 1);

const [todayData, yesterdayData, lastMonthData, lastYearData] = await Promise.all([
fetchUmamiData(todayStart, now),
fetchUmamiData(yesterdayStart, todayStart),
fetchUmamiData(lastMonthStart, now),
fetchUmamiData(lastYearStart, now)
]);

const responseData = {
today_uv: todayData?.visitors?.value ?? null,
today_pv: todayData?.pageviews?.value ?? null,
yesterday_uv: yesterdayData?.visitors?.value ?? null,
yesterday_pv: yesterdayData?.pageviews?.value ?? null,
last_month_pv: lastMonthData?.pageviews?.value ?? null,
last_year_pv: lastYearData?.pageviews?.value ?? null
};

const jsonResponse = new Response(JSON.stringify(responseData), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
}
});

event.waitUntil(cache.put(event.request, jsonResponse.clone()));

return jsonResponse;
}

真香

可以根据图片绑定自己的域名,也可以直接使用默认的

访问后你会得到返回的JSON数据

吃完刷碗

都搞定了那就可以去修改魔改后的配置项了

如果你还没魔改关于页面,可以看一下下面的文章