【问题标题】:How can I customize create in controller in Sails如何在 Sails 的控制器中自定义创建
【发布时间】:2016-04-29 20:22:07
【问题描述】:

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

// 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() ?
}

【问题讨论】:

    标签: sails.js waterline


    【解决方案1】:

    试试这样的:

    // 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
        });
    }
    

    然后创建一个检查以确保用户具有活动会话的策略。

    // 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.');
    };
    

    【讨论】:

    • 我可以这样做吗?覆盖方法create() 然后在我的方法中调用他?像 super.create()?是不是很奇怪?
    • 抱歉,一开始可能不太清楚,我添加了一条评论,希望能提高清晰度。模型方法 create() 没有被覆盖。我包含的 sn-p 应该放在 CommentController.js 中,然后通过 POST 到 /comment 调用。如果您启用了蓝图,“创建”蓝图将被覆盖(这是您想要的,因为您所做的不仅仅是保存用户/前端提供的值。
    猜你喜欢
    • 1970-01-01
    • 2018-07-22
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多