2014-01-24 164 views
1

插座具有以下策略:政策在Sails.js

// file: api/policies/foo.js 
module.exports = function(req, res, next) { 
    Model.find().done(function(err, result) { 
    if (result.length > 5) { 
     return res.forbidden(); 
    } else { 
     return next(); 
    } 
    }); 
}; 

// file: config/policies.js 
module.exports.policies = { 
    ModelController: { 
    'find': 'foo' 
    } 
}; 

和默认ModelModelController。我现在表演上两个客户端执行以下操作:

// client 1 
socket.get('/model', function(result) { console.log(result) }); 

// client 2 
var i = 10; 
while (i--) { socket.post('/model', { foo: 'bar' }); } 

客户端1实际接收10次更新,虽然他只允许接收5 当通过socket.get重新连接,我得到一个适当的权限错误。

我的问题: 在通过套接字发送更新之前检查权限的最佳做法是什么?

回答

2

您需要告诉socket.io离开它正在广播的房间。 这可以通过使用Model.unsubscribe(req.socket);来完成。

// file: api/policies/foo.js 
module.exports = function(req, res, next) { 
    Model.find().done(function(err, result) { 
     if (result.length > 5) { 
      Model.unsubscribe(req.socket); 
      return req.forbidden(); 
     } else { 
      return next(); 
     } 
    }); 
}; 

文档:socket.io rooms

代码:sails.js unsubscribe

FYI:在sails.js的未来版本Model.unsubscribe将被弃用的与req.leaveModel()取代。

+0

直视前进 - 谢谢! – pex

0

首先,如果您的策略是试图限制的模型5号,它应该是:

if (result.length > 5) {

if (!result.length > 5) {

其次,设置策略ModelController的find操作不会停止创建模型。您需要将其放在create操作上。

+0

这不是关于限制创造,而是关于接受/获取更新。 – pex