我想记录通过Cloudflare访问我网站的请求。我想我可以使用Cloudflare Workers来做这件事,但是我不希望DoS我的日志记录服务通过向我的网站发出的每个请求向它发出请求。我可以让工作包捆绑记录报告,并且每10或100只向我发出一次请求吗?
答案 0 :(得分:0)
要回答我自己的问题,是的,你可以做到这一点!您必须使用event.waitUntil
添加将在响应原始请求后运行的任务。这样做的一个问题是,如果工作人员脚本被记忆驱逐,我们将丢失batchedRequests
,但这似乎不会经常发生。
addEventListener('fetch', event => {
event.respondWith(fetchAndLog(event))
})
let batchedRequests = []
function sendRequests(){
let promises = []
for (var i=batchedRequests.length; i--;){
promises.push(fetch(...batchedRequests[i]))
}
batchedRequests = []
return Promise.all(promises)
}
/**
* Fetch and log a given request object, uploading a logging request only when five are stored
* @param {Request} request
*/
async function fetchAndLog(event) {
batchedRequests.push(["https://hookb.in/Kb88Ybq8", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
timestamp: +new Date
})
}])
if (batchedRequests.length > 4){
event.waitUntil(sendRequests())
}
return fetch(event.request)
}