Skip to content

Instantly share code, notes, and snippets.

@ScottHelme
Created November 7, 2018 12:01
Example Cloudflare Worker to batch requests.
addEventListener('fetch', event => {
event.respondWith(handle(event))
})
let batch = null;
/**
* @param {FetchEvent} event
*/
async function handle(event) {
let request = event.request
let text = await request.text()
if (batch === null) {
console.log("starting new batch with:", text)
batch = [text];
// Asynchronously accumulate and send a batch.
// event.waitUntil() tells Workers not to
// cancel this process once the response is
// returned.
event.waitUntil(handleBatch());
} else {
console.log("adding to batch:", text)
batch.push(text);
}
return new Response("accepted: " + text)
}
async function handleBatch() {
await sleep(10000)
let batchToSend = batch
batch = null
console.log("send batch:", batchToSend)
// INSERT YOUR CODE TO HANDLE A BATCH HERE
}
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment