2017-10-12 50 views
-1

我是新来的javascript后端,我目前正在学习使用node.js,express.js,sequelize.js和MySQL作为我的数据库来构建一个RESTful API。我已经成功构建了基本的Tasks API作为测试。我正在寻找反馈,看看我是否正确地做到了这一点,只要在一个控制器中使用JavaScript最佳实践即可。任何反馈将不胜感激。查看我的API控制器

当前逻辑:用户可以拥有多个任务

一切工作正常。我正在使用Passport.js中的JWT策略对用户进行身份验证。我在路由器级验证它们,然后在允许更新或删除它们自己的记录之前,通过userid在db中对它们的记录进行双重检查。不管怎么说,这里是控制器:

'use strict'; 

var jwt = require('jsonwebtoken'); 

var config = require('../config'), 
    db = require('../services/database'), 
    Task = require('../models/task'); 

var TaskController = {}; 

// GET ALL Tasks 
TaskController.get = function (req, res) { 
    if (!req.user.id) { 
     res.json({ message: 'You are not authorized.' }); 
    } else { 
     db.sync().then(function() { 
      return Task.findAll({ where: { userid: req.user.id } }).then(function (result) { 
       res.status(202).json(result); 
      }); 
     }); 
    } 
} 

// POST ONE Task 
TaskController.post = function (req, res) { 
    if (!req.body.task) { 
     res.json({ message: 'Please provide a task to post.' }); 
    } else { 
     db.sync().then(function() { 
      var newTask = { 
       userid: req.user.id, 
       task: req.body.task 
      }; 

      return Task.create(newTask).then(function() { 
       res.status(201).json({ message: 'Task Created!' }); 
      }); 
     }); 
    } 
} 

// PUT ONE Task 
TaskController.put = function (req, res) { 
    if (!req.body.task) { 
     res.json({ message: 'Please provide a task to update.' }); 
    } else { 
     db.sync().then(function() { 
      // Find task by task id and user id 
      Task.find({ where: { id: req.params.id, userid: req.user.id } }) 
       .then(function (task) { 
        // Check if record exists in db 
        if (task) { 
         task.update({ 
          task: req.body.task 
         }).then(function() { 
          res.status(201).json({ message: 'Task updated.' }); 
         }); 
        } else { 
         res.status(404).json({ message: 'Task not found.' }); 
        } 
       }); 
     }); 
    } 
} 

// DELETE ONE Task 
TaskController.delete = function (req, res) { 
    if (!req.params.id) { 
     res.json({ message: 'Please provide a task to delete.' }); 
    } else { 
     db.sync().then(function() { 
      Task.find({ where: { id: req.params.id, userid: req.user.id } }) 
       .then(function (task) { 
        if (task) { 
         task.destroy({ where: { id: req.params.id } }) 
          .then(function() { 
           res.status(202).json({ message: 'Task deleted.' }); 
          }); 
        } else { 
         res.status(404).json({ message: 'Task not found.' }); 
        } 
       }); 
     }); 
    } 
} 

module.exports = TaskController; 
+1

Stack Overflow不是代码审查平台。这里不要问这样的问题。您可以在此页面的底部找到代码审查堆栈交换。你应该删除这个问题并且在那里问。 – Rob

+0

这是一个题外话题?我要求有经验的程序员检查我的代码并指出我可能犯的任何错误。如果这不是正确的平台,那么请提出一些你喜欢的建议。谢谢 –

+0

您正在征求意见的反馈意见和最佳实践。你不会问你说过的代码中的错误。这些都是脱节主题,如帮助中心中所述。 – Rob

回答

1

TaskController.js看起来不错,但我会建议将所有的ORM逻辑(Sequelize)到一个名为TaskService.js

示例 -

TaskService.js -

... 

exports.delete = function() { 
    db.sync().then(function() { 
     Task.find({ where: { id: req.params.id, userid: req.user.id } }) 
      .then(function (task) { 
       if (task) { 
        task.destroy({ where: { id: req.params.id } }) 
         .then(function() { 
          res.status(202).json({ message: 'Task deleted.' }); 
         }); 
       } else { 
        res.status(404).json({ message: 'Task not found.' }); 
       } 
      }); 
    }); 
} 

然后在TaskController.js -

... 

const TaskService = require('./TaskService); 

... 

TaskController.delete = function(req, res) { 
    if (!req.params.id) { 
     res.json({ message: 'Please provide a task to delete.' }); 
    } else { 
     TaskService.delete(); 
    } 
} 
+1

请不要回答主题问题。回答良好的问题 并非所有的问题都可以或应该在这里得到解答。保存自己的一些挫折感,并避免试图回答以下问题...... ...不清楚或缺乏可以唯一识别问题的具体细节。 ...征求意见而非事实。“https:// stackoverflow。com/help /如何回答 – Rob

1

有一两件事我想尽可能的Javascript最佳做法将被嵌套的承诺召唤出来,这是一个有点反模式的。当你嵌套它们时,你失去了承诺链的力量,实际上创造了嵌套的回调。一旦开始尝试使用.catch()块进行错误处理,情况就会变得很奇怪。快速重构与catch块可能是这样的,即使这是基于条件的,因为仍然凌乱的任务是否在数据库中存在:

// PUT ONE Task 
TaskController.put = function (req, res) { 
    if (!req.body.task) { 
    res.json({ message: 'Please provide a task to update.' }); 
    } else { 
    db.sync() 
     .then(function() { 
     // Find task by task id and user id 
     // NOTE: we return the promise here so that we can chain it 
     // to the main promise chain started by `db.sync()` 
     return Task.find({ where: { id: req.params.id, userid: req.user.id } }); 
     }) 
     .then(function (task) { 
     // Check if record exists in db 
     if (task) { 
      task.update({ task: req.body.task }) 
      .then(function() { 
      res.status(201).json({ message: 'Task updated.' }); 
      }) 
      .catch(function (updateError) { 
      // do something with your update error 
      // catches an error thrown by `task.update()` 
      }); 
     } else { 
      res.status(404).json({ message: 'Task not found.' }); 
     } 
     }) 
     .catch(function (promiseChainError) { 
     // do something with your promiseChainError 
     // this catch block catches an error thrown by 
     // `db.sync()` and `Task.find()` 
     }); 
    } 
} 

或者,如果你更舒服同步样式代码,并有更新的节点版本V7 +的选择,这是你的职责是什么样子使用异步/ AWAIT:

// PUT ONE Task 
TaskController.put = async function (req, res) { 
    if (!req.body.task) { 
    res.json({ message: 'Please provide a task to update.' }); 
    } else { 
    try { 
     await db.sync(); 
     const task = await Task.find({ where: { id: req.params.id, userid: req.user.id } }); 

     // Check if record exists in db 
     if (task) { 
     await task.update({ task: req.body.task }); 
     res.status(201).json({ message: 'Task updated.' }); 
     } else { 
     res.status(404).json({ message: 'Task not found.' }); 
     } 
    } catch (error) { 
     // do some something with your error 
     // catches all errors thrown by anything in the try block 
    } 
    } 
} 

有大量的资源在那里大约承诺链和处理异步方法。特别检查这一项:http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/

+0

请不要回答主题问题。回答良好的问题 并非所有的问题都可以或应该在这里得到解答。保存自己的一些挫折感,并避免试图回答以下问题...... ...不清楚或缺乏可以唯一识别问题的具体细节。 ...征求意见而非事实。“https://stackoverflow.com/help/how-to-answer – Rob