问题
I have a model named Groupfeed which looks like this
module.exports = {
schema:true,
attributes:
{
groupid:
{
model:'groups',
required:true
},
postid:
{
model:'post',
required:true
},
objectid:
{
model:'objects',
required:true
},
}
};
On the client side I can subscribe to the Groupfeed model using
io.socket.get('/groupfeed')
which is done automatically by the blueprint api and then
io.socket.on('groupfeed',function(obj){console.log(obj)})
would give me updates on the model changes when I publish on the backend using
Groupfeed.publishCreate({id:4,groupid:6,postid:2,objectid:1})
What I want :-
I want a client to subscribe only to groupfeeds from a particular groupid. Eg: User X can subscribe to groupfeeds from groupid 1 (Note: A group model stores user membership for a group )
OR something like this imaginary call:
io.socket.get('/groupfeed?groupid=5')
So that when I call publishCreate with a groupid:5, only people subscribed to groupid 5's groupfeed could get an update
回答1:
You better create different rooms for groups.
CODE UNTESTED! Create a controller: NotificationsController.js
module.exports = {
subscribe: function(req, res) {
// Get groupId of user by your method
.....
.....
var roomName = 'group_' + groupId;
sails.sockets.join(req.socket, roomName);
res.json({
room: roomName
});
}
}
Somewhere you can create notification:
var roomNameForGroup = 'group_' + groupId;
sails.sockets.blast(roomNameForGroup, {id:4,groupid:6,postid:2,objectid:1});
And in your view:
io.socket.on('connect', function(){
io.socket.get('/notifications/subscribe', function(data, jwr){
if (jwr.statusCode == 200){
io.socket.on(data.room,function(obj){
console.log(obj);
});
} else {
console.log(jwr);
}
});
});
I can not test the code right now, but it looks workable.
来源:https://stackoverflow.com/questions/30253017/sails-js-subscribe-to-model-changes-scoped-by-groupid-attribute