查看我的API控制器

时间:2017-10-12 00:38:54

标签: javascript node.js express

我是javascript后端的新手,我目前正在学习使用node.js,express.js,sequelize.js和MySQL作为我的数据库来构建RESTful API。我已经成功构建了一个基本的Tasks API作为测试。我正在寻找关于我是否正确执行此操作的反馈,只要javascript最佳实践在一个控制器内。任何反馈将不胜感激。

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

一切正常。我正在使用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;

2 个答案:

答案 0 :(得分:1)

TaskController.js 看起来不错但我建议将所有ORM逻辑(Sequelize)移动到名为 TaskService.js

的文件中

示例 -

TaskService.js -

select distinct

然后在 TaskController.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.' });
                }
            });
    });
}

答案 1 :(得分:1)

就Javascript最佳实践而言,我想称之为嵌套承诺,这有点像反模式。当你嵌套它们时,你失去了承诺链的力量,实际上创建了嵌套的回调。一旦开始尝试使用.catch()块进行错误处理,事情就会开始变得怪异。带有catch块的快速重构可能看起来像这样,即使由于条件是否基于DB中是否存在任务而仍然很混乱:

// 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 +,那么您的函数可能看起来像使用async / 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/