我正在使用 firebase 函数在 android 设备上发送数据类型推送通知。我正在使用这个 index.js 脚本。当用户在 firebase 数据库中添加新消息时,我将从 firebase 数据库中获取用户 ID。
现在我想使用这个用户 ID 来获取用户的 fcmToken。
索引.js
//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Listens for new messages added to messages/:userId
exports.pushNotificationData = functions.database.ref('/messages/{userId}').onWrite( event => {
console.log('Push notification event triggered');
// Grab the current value of what was written to the Realtime Database.
var valueObject = event.data.val();
if(valueObject.photoUrl !== null) {
valueObject.photoUrl= "Sent you a photo!";
}
// Create a notification
const payload = {
data: {
title:valueObject.name,
body: valueObject.text || valueObject.photoUrl,
sound: "default"
},
};
//Create an options object that contains the time to live for the notification and the priority
const options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
const user_id = event.params.userId;
return admin.messaging().sendToDevice(user_id, payload);
});
它是 firebase 数据库中用户配置文件的结构,我想从中获取 fcmToken。
以下应该可以解决问题。您可以通过'profiles/' + user_id
使用该once()
方法查询引用来获取令牌的值。由于once()
是异步的并返回一个承诺,您必须等待承诺解析才能发送消息。
exports.pushNotificationData = functions.database
.ref('/messages/{userId}')
.onWrite(event => {
console.log('Push notification event triggered');
// Grab the current value of what was written to the Realtime Database.
var valueObject = event.data.val();
if (valueObject.photoUrl !== null) {
valueObject.photoUrl = 'Sent you a photo!';
}
// Create a notification
const payload = {
data: {
title:valueObject.name,
body: valueObject.text || valueObject.photoUrl,
sound: "default"
}
};
//Create an options object that contains the time to live for the notification and the priority
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24
};
const user_id = event.params.userId;
return admin
.database()
.ref('profiles/' + user_id)
.once('value')
.then(snapshot => {
const token = snapshot.val().fcmToken;
return admin.messaging().sendToDevice(token, payload, options);
})
.catch(error => {
console.log('Error sending message:', error);
return false;
});
});
此外,请注意您使用的是旧版本的 Cloud Functions (< v 1.0)。您应该更新到新版本和新语法。请参阅https://firebase.google.com/docs/functions/beta-v1-diff
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句