Last active 2 months ago

适用于bing每日一图项目

js Raw
1// 缓存图片数据,减少重复请求
2let cachedPictures = null;
3let cacheTimestamp = 0;
4const CACHE_TTL = 43200000; // 缓存12小时(12×60×60×1000毫秒)
5
6export async function onRequest(context) {
7 const { request } = context;
8
9 try {
10 // 使用缓存数据(如果有效)
11 const now = Date.now();
12 if (!cachedPictures || now - cacheTimestamp > CACHE_TTL) {
13 // 只在缓存过期时才重新请求
14 const origin = new URL(request.url).origin;
15 const response = await fetch(`${origin}/picture/index.json`);
16
17 if (!response.ok) {
18 return new Response('Index not found', { status: 404 });
19 }
20
21 // 直接解析并缓存
22 cachedPictures = await response.json();
23 cacheTimestamp = now;
24 }
25
26 // 随机选择一张图片
27 const randomIndex = Math.floor(cachedPictures.length * Math.random());
28 const path = cachedPictures[randomIndex].path;
29
30 // 返回重定向响应
31 return new Response(null, {
32 status: 302,
33 headers: {
34 Location: path,
35 'Cache-Control': 'no-store' // 确保每次请求都重新随机
36 }
37 });
38 } catch (error) {
39 return new Response('Error', { status: 500 });
40 }
41}