aleks aleks - 2 months ago 15
Node.js Question

How to achieve DRY routers in expres

I am building a webapp in the form of a network of sorts with basic CRUD actions. I am in the process of splitting up my router files as they are becoming rather large.

I have an 'actions' route which does things such as selecting an in individual post to view, voting on a post, viewing a profile and commending a user. I cannot seem to find a way to allow me to split these 'action' routes into a seperate file and then use them as needed in the main route.

//index.js file in routes folder
var express = require('express');
var router = express.Router();

//main route
router.route('/feed')
.get(function(req, res, next){
//some code here
}

//actions.js file in routes folder
var express = require('express');
var router = express.Router();

//vote route
router.route('/vote/:id')
.post(function(req, res, next){
//some code here
}

//item route
router.route('/item/:id')
.get(function(req, res, next){
//some code here
}


I'd like to be able to use the action routes inside of the feed routes (and other routes) So I can do things like

POST /feed/vote/postid12356
GET /feed/item/itemid123456


or even in another route called 'private-feed' using the same actions from the actions route

POST /private-feed/vote/postid12356
GET /private-feed/item/itemid123456


Without having to have these actions repeated in many routes.

Is there any way in express that this can be done?

Answer

You can extract your route handler into a separate file, let's call them controllers and then reuse the logic in some of the routes:

//controllers/action.js
module.exports = {
  get: (req, res, next) => {
     //your post logic
  }
}

///routes/item.js

const ActionController = require("../controllers/action");
router.route('/item/:id').get(ActionController.get);
module.exports = router;