Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to do DRY routers in express

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?

1 Answer

Solved:

I created a new folder called 'controllers' then a file within that called action.js. In that file I made some methods:

//action.js
module.exports = {
     getItem: (req, res, next) => {
          //do stuff for grabbing a single post
     },

     vote: (req, res, next) => {
         //do stuff for creating a vote
     }
}

Then in the index.js route file:

//index.js
var express = require('express');
var router = express.Router();
var ActionController = require("../controllers/action"); //import action.js

router.route('/feed/item/:id').post(ActionController.getItem); //new route for getting an item
router.route('/feed/vote/:id').post(ActionController.vote); //new route for making a vote

//export router
module.exports = router;