Tide: Consider "around" middleware design

Created on 20 Nov 2018  路  6Comments  路  Source: http-rs/tide

The current middleware design is based on a "before"/"after" split. We could instead have each middleware invoke the rest of the middleware/endpoint chain.

design

Most helpful comment

[Koa] also uses "around" middleware approach. Koa goes one step further; everything is middleware, even [the router]! In this way, fallback handler can be implemented as the deepest middleware on the chain. When the router fails to route, it'd invoke the next middleware.

All 6 comments

(I have a bunch of thoughts/design constraints here, will write them up ASAP)

[Koa] also uses "around" middleware approach. Koa goes one step further; everything is middleware, even [the router]! In this way, fallback handler can be implemented as the deepest middleware on the chain. When the router fails to route, it'd invoke the next middleware.

I know this was merged recently, but can you guys go into a little detail as to the pros of such a middleware design?

For sure! Here are some thoughts:

  • First, we can easily provide constructors for before/after-style middleware as well. At some point in the PR, @tirr-c had both available. So we don't lose anything, and if we find it's more convenient to write in that style, we can give a way to do it.

  • This "around" style middleware makes it easier to pass information from "before" to "after" computations; you don't have to use extensions to do so any more, you just use let.

  • The original middleware style forced an allocation for every middleware on every request. In this new setup, if you're doing synchronous work in middleware (which is often the case) you can usually avoid this allocation.

  • The middleware interface itself is a bit simpler (IMO)

Because it's possible to provide easy before/after constructors on top of the new interface, I don't see a lot of downsides.

Awesome, that makes a lot of sense. One thing I'm still not entirely sure of is how data is shared between different middleware and between middleware and the endpoint.

Am I right in thinking that the Data in a RequestContext will be used for sharing data between middleware and endpoints? I'm still not sure how it will be shared between two middlewares though.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Nemo157 picture Nemo157  路  6Comments

milesgranger picture milesgranger  路  6Comments

fasterthanlime picture fasterthanlime  路  4Comments

yoshuawuyts picture yoshuawuyts  路  6Comments

tirr-c picture tirr-c  路  6Comments