简体   繁体   English

Express.js最佳做法

[英]Express.js Best Practices

I have defined the following express route(s) in server.js: 我在server.js中定义了以下快速路由:

app.get('/adfeed', adfeed.findAll);

app.get('/subscriptions', subscriptions.findAll);

app.get('/cronjob/match', cronjob.match);

Function called when performing GET on /adfeed is: 在/ adfeed上执行GET时调用的函数是:

exports.findAll = function(req, res) {
  mongo.Db.connect(mongoUri, function (err, db) {
    db.collection('adfeed', function(er, collection) {
      collection.find().toArray(function(err, items) {
        res.send(items);
        db.close();
      });
    });
  });
}

Function called when performing GET on /subscriptions is: 在/ subscriptions上执行GET时调用的函数是:

exports.findAll = function(req, res) {
    console.log("Get All Subscriptions");
  mongo.Db.connect(mongoUri, function (err, db) {
    db.collection('subscriptions', function(err, collection) {
      collection.find().toArray(function(err, items) {
        res.send(items);
        db.close();
      });
    });
 });
}

QUESTION: /cronjob/match needs to use BOTH the above functions. 问题:/ cronjob / match需要同时使用以上功能。 Is it best practice to call an Express route from an Express route? 从Express路由呼叫Express路由是最佳实践吗? Is there a better way to do this without duplicating code all over the place? 有没有更好的方法来做到这一点而又无需在各处复制代码?

Thanks for help! 感谢帮助!

You could avoid code duplication using a function that generates the function you want, which is easier than it sounds: 您可以使用生成所需函数的函数来避免代码重复,这比听起来容易:

function findStuffFn(typeOfStuff) {
  return function (err, db) {
    db.collection(typeOfStuff, function(err, collection) {
      collection.find().toArray(function(err, items) {
        res.send(items);
        db.close();
      });
    });
  };
}

This is will return a function that is just like your code above, but with a parameter replacing the string. 这将返回一个函数,就像上面的代码一样,但是用参数代替了字符串。 Thus your code could look like this: 因此,您的代码可能如下所示:

exports.findAll = function(req, res) {
  mongo.Db.connect(mongoUri, findStuffFn('adfeed'));
};

and

exports.findAll = function(req, res) {
  console.log("Get All Subscriptions");
  mongo.Db.connect(mongoUri, findStuffFn('subscriptions'));
};

This is where the idea of Separation of Concerns comes into play. 在这里,关注点分离的想法开始发挥作用。 In this case you want a separate nodejs module which makes the database calls. 在这种情况下,您需要一个单独的nodejs模块来进行数据库调用。 The module exposes two methods. 该模块公开了两种方法。

/adfeed calls function A /subscriptions calls function B And, /cronjob calls both functions. / adfeed调用函数A / subscriptions调用函数B而且,/ cronjob调用这两个函数。

By using SoC you are able to increase the reuse of code. 通过使用SoC,您可以提高代码的重用性。 Your controller methods are not directly calling db code. 您的控制器方法没有直接调用数据库代码。 They are responsible for only one thing. 他们只负责一件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM