Reputation: 2090
I have a set of routes that are defined in a routes.js file like so:
const express = require('express');
const router = express.Router();
const controller = require('../controllers/mycontroller');
router.get('/', controller.home);
router.get('/about', controller.about);
...
What I want to do is to be able to add some meta-data to each of these definitions, like so:
router.get('/', controller.home).metadata({title: 'Home Page', internal: true});
And then be able to read them in a for loop:
router.stack.forEach((route) => {
const metadata = ???
});
How can I achieve this? I would need this information inside the controller as well, so in controller.home
I will need to pass title
to the appropriate template.
Can I use bind()
for this? I thought maybe I can do:
router.get('/', controller.home).bind(key: 'value');
so that in the controller, I can do this.key
. But how can I access this key in a router.stack
for loop?
Upvotes: 2
Views: 512
Reputation: 2090
Not sure if this is the best approach, but I ended up defining a "route generating" function that takes in a url, title, metadata, and a list of middlewares and defines an appropriate get
route. This acts as a small wrapper around the router module.
in utils/router.js
:
const express = require('express');
const router = express.Router();
const addTitle = (title) => (req, res, next) => {
res.locals.title = title;
next();
}
const get = router.get;
router.get = function(url, title, internal, ...middlewares) {
// do what's needed with metadata here
// for example add them to the list of pages to be crawled
get.call(router, url, addTitle(title), ...middlewares);
};
module.exports = router;
and in routes/my.routes.js
:
const express = require('express');
const router = require('../utils/router');
const controller = require('../controllers/mycontroller');
router.get('/', 'Home', internal=true, controller.home);
...
module.exports = router;
Upvotes: 1