How to achieve DRY routers in express

邮差的信 提交于 2021-02-08 10:11:37

问题


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:


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;


来源:https://stackoverflow.com/questions/39685174/how-to-achieve-dry-routers-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!