kwhitley / itty-router

A little router.
MIT License
1.75k stars 78 forks source link

Running an handler after response is returned #77

Closed danbars closed 2 years ago

danbars commented 2 years ago

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?

kwhitley commented 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!

danbars commented 2 years ago

Awesome, thanks 👍