Ghost/core/server/services/route/ParentRouter.js
Hannah Wolfe 016ee17ebb
Rework route service to prevent circular dependencies (#9229)
refs #9192, refs #9178  

After trying to progress with current implementation, it became clear that the route service can't control the boot sequence, because then we end up with circular dependencies between the route service and the channel service.

The route service now exposes:
-  a siteRouter 
- a way for apps to register routes.
- ParentRouter base class for other modules to use
- the registry

...

- moved the default route setup back to site/routes.js 🙈
- moved the parent channel router back to the channel service (this makes way more sense imo)
- this structure prevents circular dependencies
- split the registry out into it's own thing
- fixed-up various bits of tests and comments
- DEBUG will print a list of routes 🎉
2017-11-09 13:58:22 +00:00

49 lines
1.4 KiB
JavaScript

'use strict';
/**
* # Router
*
* A wrapper around express.Router
* Intended to be extended anywhere that routes need to be registered in Ghost
* Only allows for .use and .get at the moment - we don't have clear use-cases for anything else yet.
*/
var debug = require('ghost-ignition').debug('services:routes:ParentRouter'),
express = require('express'),
// This the route registry for the whole site
registry = require('./registry');
/**
* We expose a very limited amount of express.Router via specialist methods
*/
class ParentRouter {
constructor(name) {
this.name = name;
this._router = express.Router({mergeParams: true});
}
mountRouter(path, router) {
if (arguments.length === 1) {
router = path;
debug(this.name + ': mountRouter: ' + router.name);
this._router.use(router);
} else {
registry.set(this.name, path);
debug(this.name + ': mountRouter: ' + router.name + ' at ' + path);
this._router.use(path, router);
}
}
mountRoute(path, controller) {
debug(this.name + ': mountRoute for', path, controller.name);
registry.set(this.name, path);
this._router.get(path, controller);
}
router() {
// @TODO: should this just be the handler that is returned?
// return this._router.handle.bind(this._router);
return this._router;
}
}
module.exports = ParentRouter;