Express: How to pass app-instance to routes from a different file?

后端 未结 8 1080
误落风尘
误落风尘 2020-11-29 16:34

I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve thi

8条回答
  •  孤街浪徒
    2020-11-29 16:56

    1. To make your db object accessible to all controllers without passing it everywhere: make an application-level middleware which attachs the db object to every req object, then you can access it within in every controller.
    // app.js
    let db = ...;  // your db object initialized
    const contextMiddleware = (req, res, next) => {
      req.db=db;
      next();
    };
    app.use(contextMiddleware);
    
    1. to avoid passing app instance everywhere, instead, passing routes to where the app is
    // routes.js  It's just a mapping.
    exports.routes = [
      ['/', controllers.index],
      ['/posts', controllers.posts.index],
      ['/posts/:post', controllers.posts.show]
    ];
    
    // app.js
    var { routes }    = require('./routes');
    routes.forEach(route => app.get(...route));
    // You can customize this according to your own needs, like adding post request
    

    The final app.js:

    // app.js
    var express   = require('express');
    var app       = express.createServer();
    
    let db = ...;  // your db object initialized
    const contextMiddleware = (req, res, next) => {
      req.db=db;
      next();
    };
    app.use(contextMiddleware);
    
    var { routes }    = require('./routes');
    routes.forEach(route => app.get(...route));
    
    app.listen(3000, function() {
      console.log('Application is listening on port 3000');
    });
    

    Another version: you can customize this according to your own needs, like adding post request

    // routes.js  It's just a mapping.
    let get = ({path, callback}) => ({app})=>{
      app.get(path, callback);
    }
    let post = ({path, callback}) => ({app})=>{
      app.post(path, callback);
    }
    let someFn = ({path, callback}) => ({app})=>{
      // ...custom logic
      app.get(path, callback);
    }
    exports.routes = [
      get({path: '/', callback: controllers.index}),
      post({path: '/posts', callback: controllers.posts.index}),
      someFn({path: '/posts/:post', callback: controllers.posts.show}),
    ];
    
    // app.js
    var { routes }    = require('./routes');
    routes.forEach(route => route({app}));
    

提交回复
热议问题