Mounting Express Middleware
When mounting Express middleware, the middleware being mounted may need to have some awareness of the parent Express application.
So, let's say we are mounting our cool middleware like so within some module that uses Express:
app.use( '/someRoute', ourCoolMiddleware({ debug: false } ) );
How can ourCoolMiddleware
detect when it was mounted? By using the mount
event. Within our ourCoolMiddleware module we would declare a mount
event, as seen bellow:
// Initialize our middleware (most likely in a separate module)
module.exports = require( 'express' )();
// Add some logic/routes.
module.exports.get( '/getStuff', someFunction );
module.exports.post( '/postStuff', someOtherFunction );
// Here comes the important part!
module.exports.on( 'mount', onMount );
/**
* Our way of knowing we were mounted to another Express application.
*/
function onMount( parentApp ) {
// this <- Instance of our Express middleware.
// this.parent <- Instance (app) that we were mounted to.
// this.mountpath <- The path used to mount to parent.
// this.parent.mountpath <- Was the parent Express app mounted also?
console.log( "I was just mounted to [%s] path!", this.mountpath );
if( this.parent.mountpath ) {
console.log( "My parent was also mounted!" );
}
}
Within the onMount
example function above we have access to both Express applications, the one being mounted this
and the instanced being mounted to this.parent
. There is also this.mountpath
which can be used to detect the path (in our example `/someRoute') that was used to mount our child middleware.
Manipulating The Parent
This makes it possible for us to add a route to the parent or perhaps evaluate the routes on the parent by analyzing this.parent._stack
as well as get access to all other functions of the parent app
.