Skip to content

Commit

Permalink
优化list相关接口的响应速度
Browse files Browse the repository at this point in the history
  • Loading branch information
MarSeventh committed Dec 20, 2024
1 parent a3e936c commit 83bba59
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 17 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Add Features:
- 管理端支持拉黑上传IP(Dashboard->用户管理->允许上传)
- 管理端批量操作支持按照用户选择的顺序进行([#issue124](https://github.com/MarSeventh/CloudFlare-ImgBed/issues/124)
- `random`接口优化,减少KV操作次数,增加`content`参数,支持返回指定类型的文件
- 接入CloudFlare Cache API,提升 list 相关接口访问速度

## 2024.12.14

Expand Down
16 changes: 13 additions & 3 deletions functions/api/manage/delete/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,24 @@ export async function onRequest(context) {
await env.img_url.delete(params.id);
const info = JSON.stringify(params.id);

// 清除CDN缓存,包括图片和randomFileList接口的缓存
const randomFileListUrl = `https://${url.hostname}/api/randomFileList`;
// 清除CDN缓存
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-Auth-Email': `${env.CF_EMAIL}`, 'X-Auth-Key': `${env.CF_API_KEY}`},
body: `{"files":["${ cdnUrl }", "${ randomFileListUrl }"]}`
body: `{"files":["${ cdnUrl }"]}`
};
await fetch(`https://api.cloudflare.com/client/v4/zones/${ env.CF_ZONE_ID }/purge_cache`, options);
// 清除api/randomFileList API缓存
try {
const cache = caches.default;
// 通过写入一个max-age=0的response来清除缓存
const nullResponse = new Response(null, {
headers: { 'Cache-Control': 'max-age=0' },
});
await cache.put(`${url.origin}/api/randomFileList`, nullResponse);
} catch (error) {
console.error('Failed to clear cache:', error);
}

return new Response(info);
} catch (e) {
Expand Down
10 changes: 8 additions & 2 deletions functions/api/manage/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export async function onRequest(context) {
next, // used for middleware or to fetch assets
data, // arbitrary space for passing data between middlewares
} = context;

let allRecords = [];
let cursor = null;

Expand All @@ -23,6 +24,11 @@ export async function onRequest(context) {
} while (cursor);

const info = JSON.stringify(allRecords);
return new Response(info);
let res = new Response(info, {
headers: {
"Content-Type": "application/json",
}
});

}
return res;
}
27 changes: 19 additions & 8 deletions functions/api/randomFileList.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ export async function onRequest(context) {
return new Response('Error: Please configure KV database', { status: 500 });
}

// 看缓存中是否有记录,有则直接返回
const cache = caches.default;
const cacheRes = await cache.match(request.url);
if (cacheRes) {
return cacheRes;
}

// 缓存未命中
let allRecords = [];
let cursor = null;

Expand All @@ -43,14 +51,17 @@ export async function onRequest(context) {
}
});

// 返回所有记录,设置缓存时间为1天
// 返回所有记录
const info = JSON.stringify(allRecords);
return new Response(info,
{
headers: {
"Content-Type": "application/json",
"Cache-Control": "public, max-age=86400",
}
const res = new Response(info,{
headers: {
"Content-Type": "application/json",
}
);
});

// 缓存结果,缓存时间为24小时
await cache.put(request.url, res.clone(), {
expirationTtl: 24 * 60 * 60
});
return res;
}
18 changes: 14 additions & 4 deletions functions/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export async function onRequestPost(context) { // Contents of context object
// 清除CDN缓存
const cdnUrl = `https://${url.hostname}/file/${fullId}`;
await purgeCDNCache(env, cdnUrl, url);


// ====================================不同渠道上传=======================================
// 出错是否切换渠道自动重试,默认开启
Expand Down Expand Up @@ -441,15 +441,25 @@ async function getFilePath(env, file_id) {
}

async function purgeCDNCache(env, cdnUrl, url) {
// 清除CDN缓存,包括图片和randomFileList接口的缓存
const randomFileListUrl = `https://${url.hostname}/api/randomFileList`;
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-Auth-Email': `${env.CF_EMAIL}`, 'X-Auth-Key': `${env.CF_API_KEY}`},
body: `{"files":["${ cdnUrl }", "${ randomFileListUrl }"]}`
body: `{"files":["${ cdnUrl }"]}`
};

await fetch(`https://api.cloudflare.com/client/v4/zones/${ env.CF_ZONE_ID }/purge_cache`, options);

// 清除api/randomFileList API缓存
try {
const cache = caches.default;
// await cache.delete(`${url.origin}/api/randomFileList`); delete有bug,通过写入一个max-age=0的response来清除缓存
const nullResponse = new Response(null, {
headers: { 'Cache-Control': 'max-age=0' },
});
await cache.put(`${url.origin}/api/randomFileList`, nullResponse);
} catch (error) {
console.error('Failed to clear cache:', error);
}
}

function isExtValid(fileExt) {
Expand Down

0 comments on commit 83bba59

Please sign in to comment.