【发布时间】:2017-10-31 15:36:18
【问题描述】:
我在之前的项目中使用过这个 Firebase 数据库代码:
const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value');
我现在正在尝试将其转换为 Firestore。我基本上是在发送通知时尝试让我的用户 fcm。我尝试了很多东西,但还没有看到实现这一目标的新方法。
编辑:这是我的代码。
exports.sendFavoriteNotification = functions.firestore.document('users/{userUid}/notifications/{notificationId}').onCreate(event => {
const notification = event.data.data();
const user = event.params.userUid;
const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value');
// Get the follower profile.
const getProfilePromise = admin.auth().getUser(notification.sender);
return Promise.all([getDeviceUser, getProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const liker = results[1];
// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
//console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log('Fetched follower profile', liker);
// Notification details.
const payload = {
notification : {
title : 'You have a new like!',
body : `${liker.displayName} just liked your photo.`,
badge: '1',
sound: 'default'
}
};
// Listing all tokens.
var tokens = admin.firestore.ref(`/users/${notification.to}/`).get('fcm');
// Send notifications to all tokens.
admin.messaging().sendToDevice(tokens.data(), payload);
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.update({
fcm: FieldValue.delete()
}));
}
}
});
return Promise.all(tokensToRemove);
});
});
});
【问题讨论】:
-
您好——您能告诉我们更多关于您的数据模型和代码的信息吗?
-
是的,其他一切都在工作,我只是举了 firebase 为 fcm 通知提供的例子。基本上现在我只需要能够检索 fcms,然后在函数中返回它们,以便它发送通知。
-
我很高兴听到其他一切正常!但是,帮助您需要更多信息。你的文件是什么样的?
-
好的,我添加了我的代码。 fcm 变量不起作用,但一旦我能得到数据,我就知道如何解决这些问题。
-
我的通知文档是带有元数据字段的随机键。我正在尝试从用户数据中的集合中获取 fcm,其中 fcm 令牌是文档 ID。
标签: javascript node.js google-cloud-functions google-cloud-firestore