Last active
February 1, 2019 15:00
-
-
Save kamal/97676086862aecf84f1900e65320763b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener("fetch", event => { | |
event.respondWith(handleRequest(event.request)); | |
}); | |
/** | |
* Multiplex requests to a fixed list of destinations. | |
* | |
* It is intentional that we only support rewriting the incoming request URL to | |
* that of the destination. Everything else on the request is untouched. | |
* | |
* In this particular use case, we are multiplexing to hosts that want to | |
* receive SendGrid's webhook payload. This Cloudflare Worker was created as a | |
* workaround to SendGrid's limitation of supporting only a single webhook URL. | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
const urls = ["https://postb.in/b/ilhoNrlv", "https://postb.in/b/5yWt1wim"]; | |
const fetchPromises = urls.map(url => | |
fetch(new Request(url, request.clone())) | |
); | |
try { | |
const responses = await Promise.all(fetchPromises); | |
// "The Promise returned from fetch() won’t reject on HTTP error status even | |
// if the response is an HTTP 404 or 500. Instead, it will resolve normally | |
// (with ok status set to false), and it will only reject on network failure | |
// or if anything prevented the request from completing." | |
// | |
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch | |
const failedRequests = responses.filter(response => !response.ok); | |
if (failedRequests.length > 0) { | |
return _respondWithFailure( | |
`Failed to multiplex request to ${failedRequests.length} destinations` | |
); | |
} | |
return _respondWithSuccess( | |
`Successfully multiplexed request to ${fetchPromises.length} destinations` | |
); | |
} catch (err) { | |
return _respondWithFailure(err); | |
} | |
} | |
function _respondWithSuccess(message) { | |
return new Response(message, { status: 200, statusText: "OK" }); | |
} | |
function _respondWithFailure(error) { | |
return new Response(error, { | |
status: 500, | |
statusText: "Internal Server Error" | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment