js
· 1.2 KiB · JavaScript
Raw
// 缓存图片数据,减少重复请求
let cachedPictures = null;
let cacheTimestamp = 0;
const CACHE_TTL = 43200000; // 缓存12小时(12×60×60×1000毫秒)
export async function onRequest(context) {
const { request } = context;
try {
// 使用缓存数据(如果有效)
const now = Date.now();
if (!cachedPictures || now - cacheTimestamp > CACHE_TTL) {
// 只在缓存过期时才重新请求
const origin = new URL(request.url).origin;
const response = await fetch(`${origin}/picture/index.json`);
if (!response.ok) {
return new Response('Index not found', { status: 404 });
}
// 直接解析并缓存
cachedPictures = await response.json();
cacheTimestamp = now;
}
// 随机选择一张图片
const randomIndex = Math.floor(cachedPictures.length * Math.random());
const path = cachedPictures[randomIndex].path;
// 返回重定向响应
return new Response(null, {
status: 302,
headers: {
Location: path,
'Cache-Control': 'no-store' // 确保每次请求都重新随机
}
});
} catch (error) {
return new Response('Error', { status: 500 });
}
}
| 1 | // 缓存图片数据,减少重复请求 |
| 2 | let cachedPictures = null; |
| 3 | let cacheTimestamp = 0; |
| 4 | const CACHE_TTL = 43200000; // 缓存12小时(12×60×60×1000毫秒) |
| 5 | |
| 6 | export 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 | } |