Closed danbars closed 2 years ago
Hey @danbars!
Absolutely this is a pattern that is used, for example to embed CORS heads into responses before sending. The way to achieve this is simply chain onto the router.handle
promise:
// pseudocode
const logResponse = response => log(response) // assumes "log()" returns the response as well
router
.handle(request, env) // assuming you return a valid Response from this...
.then(response => {
// do something to response
return response // and pass it along
})
.then(logResponse) // basically tacking on response middleware
.then(response => {
// do something else to response
return response // and pass it along
})
Anecdotally (and unrelated), there are no rules within itty to enforce what may be passed through (Responses are just one option), so you could use this for all sorts of weird things that I haven't thought of.
Hope this helps!
Awesome, thanks 👍
Hi,
In some cases you'd want to run common code after one of the handlers returned a
Response
but before it was returned to the client. Some examples:For all these cases I'd like to be able to add handlers that will run as middleware on the way out.
What do you think? Is there another pattern to achieve that?