您应该在上面的节点上触发函数,如下所示。并访问
instanceId_token
通过
changes.after.val()
.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref("users/{userId}")
.onWrite((changes, context) => {
const userId = context.params.userId;
console.log("user-id", userId);
const notificationToken = changes.after.val().instanceId_token;
console.log("deviceToken", notificationToken);
var payload = {
data: {
title: "Welcome to My Group",
message: "You may have new messages"
}
};
return admin.messaging().sendToDevice(notificationToken, payload)
.catch(function (error) {
console.log("Error sending message: ", error);
})
});
如果你加上
instanceid_令牌
只有在创建了用户之后,才应该使用
onUpdate()
(它“在数据更新时触发”,而
onWrite()
“创建、更新或删除数据时触发”)。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref("users/{userId}")
.onUpdate((changes, context) => {
const userId = context.params.userId;
console.log("user-id", userId);
const notificationToken = changes.after.val().instanceId_token;
console.log("deviceToken", notificationToken);
if (notificationToken === undefined) {
console.log("notificationToken === undefined");
return false;
} else {
var payload = {
data: {
title: "Welcome to My Group",
message: "You may have new messages"
}
};
return admin.messaging().sendToDevice(notificationToken, payload)
.catch(function (error) {
console.log("Error sending message: ", error);
})
}
});
还要注意你不应该这样做
return admin.messaging().sendToDevice(notificationToken, payload)
.then(function (response) {
return console.log("Successfully sent message: ", response);
})
.catch(function (error) {
return console.log("Error sending message: ", error);
});
因为在这种情况下,您不会返回“在函数中完成所有异步工作时解决”的承诺。(见答案)
question
)
所以只要把SendtoDevice的承诺还给我就行了(参见
doc
),如下所示:
return admin.messaging().sendToDevice(notificationToken, payload)
.catch(function (error) {
console.log("Error sending message: ", error);
});