mirror of
https://github.com/TryGhost/Ghost.git
synced 2025-01-06 22:40:14 -05:00
ParentRouter: Added wrapper for Express Router
refs #9601 - if you call `express.Router()`, the router's name is always "router" - that is caused by the closure behaviour in express: - https://github.com/expressjs/express/blob/4.16.3/lib/router/index.js#L46 - Ghost creates a couple of express routers for dynamic routing - it depends how much you configure in your routes.yaml file - but every router is called "router" - this is hard to work with - with this router wrapping logic, we are able to give each router an exact name If you enable `DEBUG=ghost:services:routing:*`, you have seen this before > ghost:services:routing:ParentRouter site: mountRouter: router +0ms With the wrapper logic, you will see: > ghost:services:routing:ParentRouter site: mountRouter: StaticPagesRouter +0ms - furthermore, if you have to access the router stack (`app.router.stack`), you can easily identify and find router instances by name
This commit is contained in:
parent
8a10826518
commit
691daa2a49
1 changed files with 20 additions and 3 deletions
|
@ -10,11 +10,30 @@ const debug = require('ghost-ignition').debug('services:routing:ParentRouter'),
|
|||
EventEmitter = require('events').EventEmitter,
|
||||
express = require('express'),
|
||||
_ = require('lodash'),
|
||||
setPrototypeOf = require('setprototypeof'),
|
||||
security = require('../../lib/security'),
|
||||
urlService = require('../url'),
|
||||
// This the route registry for the whole site
|
||||
registry = require('./registry');
|
||||
|
||||
function GhostRouter(options) {
|
||||
const router = express.Router(options);
|
||||
|
||||
function innerRouter(req, res, next) {
|
||||
return innerRouter.handle(req, res, next);
|
||||
}
|
||||
|
||||
setPrototypeOf(innerRouter, router);
|
||||
|
||||
Object.defineProperty(innerRouter, 'name', {
|
||||
value: options.parent.name,
|
||||
writable: false
|
||||
});
|
||||
|
||||
innerRouter.parent = options.parent;
|
||||
return innerRouter;
|
||||
}
|
||||
|
||||
/**
|
||||
* We expose a very limited amount of express.Router via specialist methods
|
||||
*/
|
||||
|
@ -25,7 +44,7 @@ class ParentRouter extends EventEmitter {
|
|||
this.identifier = security.identifier.uid(10);
|
||||
|
||||
this.name = name;
|
||||
this._router = express.Router({mergeParams: true});
|
||||
this._router = GhostRouter({mergeParams: true, parent: this});
|
||||
}
|
||||
|
||||
mountRouter(path, router) {
|
||||
|
@ -61,8 +80,6 @@ class ParentRouter extends EventEmitter {
|
|||
}
|
||||
|
||||
router() {
|
||||
// @TODO: should this just be the handler that is returned?
|
||||
// return this._router.handle.bind(this._router);
|
||||
return this._router;
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue