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?
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
getroute. This acts as a small wrapper around the router module.in
utils/router.js:and in
routes/my.routes.js: