【问题标题】:Reduce code repetition in express API route减少快速 API 路由中的代码重复
【发布时间】:2015-07-17 21:18:16
【问题描述】:

我正在学习 express,目前正在编写一个 API,并且具有以下结构:

app.route('/api/brief/:_id')
  .get(function(req, res, next) {
    // Check if the _id is a valid ObjectId
    if (mongoose.Types.ObjectId.isValid(req.params._id)) {
      // Do something
    }else{
      // Error
    }
  })
  .put(function(req, res, next) {
    // Check if the _id is a valid ObjectId
    if (mongoose.Types.ObjectId.isValid(req.params._id)) {
      // Do something
    }else{
      // Error
    }
  })
  .delete(function(req, res, next) {
    // Check if the _id is a valid ObjectId
    if (mongoose.Types.ObjectId.isValid(req.params._id)) {
      // Do something
    }else{
      // Error
    }
  });

理想情况下,我希望避免重复(检查 ID 的有效性)。

有没有办法可以构造路线以避免重复?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    有几种方法可以解决它。有app.all()方法:

    app.all("/api/*", function(req, res, next) {
    
        if (req.params._id) {
    
            if (mongoose.Types.ObjectId.isValid(req.params._id)) {
                return next();
            }
            else {
                // error handle
            }
        }
        next();
    });
    

    就我个人而言,我不喜欢包罗万象。我宁愿更明确:

    function validateMongooseId (req, res, next) {
    
        if ( mongoose.Types.ObjectId.isValid(req.params._id) ) {
            return next();
        }
        else {
            // error handle
        }
    }
    
    function handleGet(req, res, next) {}
    function handlePost(req, res, next) {}
    function handlePut(req, res, next) {}
    
    app.post("/api/brief", handlePost);
    app.get("/api/brief/:_id", validateMongooseId, handleGet);
    app.put("/api/brief/:_id", validateMongooseId, handlePut);
    

    我把.post() 放在那里是为了说明我为什么不喜欢包罗万象。它显然不适用于该端点。您可能有其他适用于它的中间件函数,因此我宁愿将它们明确地放在使用它们的端点上。

    【讨论】:

    • 真的很有用,谢谢。通过使用app.all("/api/brief/:_id"…,我实际上能够很容易地实施第一个建议(同时绕过POST
    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多