sails.js - 如何在 Sails 的 Controller 中自定义创建

标签 sails.js waterline

我创建了一个具有一对一关联的评论模型。

// api/models/Comment.js
module.exports = {
  attributes: {
    user: {
      model: 'user',
      unique: true,
    },

    comment: {
      type: 'string'
    },
  }
};

以及用于创建它的 HTML 表单。

<form method="POST" action="/comment">
    <!-- send logged user -->
    <input type="text" name="workingRegion" placeholder="City">
    <input type="submit" value="submit">
</form>

如何在创建评论之前添加 userId(假设用户使用 Passport.js 登录(req.session.user 中的 userId)?

我正在考虑在 CommentController 中自定义 create(),但我不知道如何实现。 创建:函数(req,res){ if (!req.session && !req.session.user)//使用 Passport //错误

    //save() ?
}

最佳答案

尝试这样的事情:

// api/controllers/CommentController.js

create: function(req, res) { 
    var params = req.params.all();
    params.user = req.session.user.id;

    Comment.create(params)
    .exec(function(err, comment) {
        //do stuff here
    });
}

然后创建一个策略来检查以确保用户具有事件 session 。

// api/policies/sessionAuth.js

module.exports = function(req, res, next) {
  // this assumes you created an "authenticated" flag for the session
  // when the user logged in
  if (req.session.authenticated) {
    return next();
  }

  return res.forbidden('You are not permitted to perform this action.');
};

关于sails.js - 如何在 Sails 的 Controller 中自定义创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946839/

相关文章:

node.js - Sails mongodb 缺少连接处理

git - 将 NodeJS 应用程序部署到 Azure 网站时,从部署.cmd 中的 pages.json 安装 NPM 包失败?

node.js - 使用 NPM 安装 Node Sailsjs 包

node.js - Sails 0.10 ModelIdentity.subscribe 或 .watch 和 publishCreate()?

javascript - Sails.js + Grunt "Cannot find module"错误

node.js - 水线: Trying to access a collection string that is not defined

javascript - 如何从 Sails JS Waterline 集合中获取指定字段的列表?

javascript - 使用附加数据将函数传递给 sails.js

javascript - 在开发期间在特定 IP 地址上运行 sails.js

mysql - 二进制字段,Waterline ORM