我正在使用sails.socket发送消息。我的要求是,我必须在发送消息成功后发送推送通知。怎么可能。请参阅我编写的代码。
sendChatMessage(chatMessage, function() {
// calling push notification when a chat message send
var serverKey = req.options.settingsKeyValue.PUSH_SERVER_KEY;
var typeData = { type:1, data:{type:1} };
var pushData = { title:'New Message', body: data };
pusherService.pushFcm(serverKey,typeData,pushData,toId, function(err, result) {
if(err) {
return res.json(200, {status:1, status_type: 'Success', message: 'Error in sending the message'});
}else{
return res.json(200, {status:1, status_type: 'Success', message: 'You have successfully send the message'});
}
});
});
function sendChatMessage(){
var socketRoom = "userRoom_"+toId;
var roomsSubcribers = sails.sockets.subscribers(socketRoom);
console.log("roomsSubcribers");
console.log(roomsSubcribers);
var data = {
text: message,
from_id: fromId,
from_name: userResult[0].firstName+' '+userResult[0].lastName, from_img : userResult[0].profilePhoto,
};
sails.sockets.broadcast(socketRoom,{
type : "chat",
message : data,
});
callback(chatMessage);
}
答案 0 :(得分:0)
这些代码块对我来说没问题......你只需将它们放在应用程序中的正确位置即可。你试过这个吗?
您肯定需要在sendChatMessage
函数定义和回调函数中命名一些参数。
也许你需要这样的东西:
// in some controller
// notice the named arguments 'options' and 'callback'
var sendChatMessage = function(options, callback){
var socketRoom = "userRoom_"+options.toId;
var roomsSubcribers = sails.sockets.subscribers(socketRoom);
console.log("roomsSubcribers");
console.log(roomsSubcribers);
var data = {
text: options.message,
from_id: options.fromId,
from_name: options.fromName,
from_img : options.fromImg,
};
sails.sockets.broadcast(socketRoom,{
type : "chat",
message : data,
});
callback(data);
};
module.exports = {
someMethod: function(req, res) {
// do some work, including defining / getting all options
var options = {
toId: 123,
fromId: 456,
message: 'test message',
fromName: 'test user',
fromImg: 'some/image.jpg' // don't know if you need a source here or what
};
// invoke your function - notice the named argument in the callback
sendChatMessage(options, function(data) {
// calling push notification when a chat message send
var serverKey = req.options.settingsKeyValue.PUSH_SERVER_KEY;
var typeData = { type:1, data:{type:1} };
var pushData = { title:'New Message', body: data };
pusherService.pushFcm(serverKey,typeData,pushData,toId, function(err, result) {
if(err) {
return res.json(200, {status:1, status_type: 'Success', message: 'Error in sending the message'});
}else{
return res.json(200, {status:1, status_type: 'Success', message: 'You have successfully send the message'});
}
});
});
},
};
我无法知道这是否是使用所有插件等的正确方法,但将这些部分放在一起似乎是有道理的。
最后请注意,当您定义自己的回调时,最好将第一个参数作为错误对象,并检查回调正文中收到的错误。成功后,您可以返回空错误,例如callback(null, data);
。
希望这有用。