strongloop/loopback — pull request #908 by bajtos (2014-12-10 10:53:16+00:00)
Title: Rework phased middleware, fix several bugs

Bugs fixed (see #895):

- express helpers like `req.get` are now available in middleware
handlers registered via `app.middleware`

- `req.url` does not include the mountpath prefix now, this is
consistent with the behaviour of `app.use`

The implementation of phased middleware was completely rewritten.

- We no longer use Phase and PhaseList objects from loopback-phase.
- Handler functions are registered via the `Layer` mechanism used by express router
- The app keeps the layers sorted according to phases.

@dougwilson Do you see any major flaws in this new implementation? We are duplicating two parts from express application & router, which I am not happy about, but I consider it a low risk.

There are three express changes that would simplify this implementation. Is any of them something you would consider accepting to express?
- Emit an event on `app._router` whenever a new Layer (middleware or route) was added. That way loopback does not have to override `app.use` and `app.route` and can listen for this event instead.
- Expose the code wrapping express apps into a middleware function so that we can call it directly from loopback. That way loopback does not have to keep a copy of `wrapHandlerIfAnExpressApp`.
- Refactor `router.use` so that consumers can add extra layer properties, e.g. by extracting a method for creating a new middleware Layer instance. That way loopback does not need to keep a copy of that factory code.

/to @raymondfeng please review
/cc @ritch