【发布时间】:2018-03-15 04:14:18
【问题描述】:
我想创建一个 firebase 函数,它会在表中推送新条目时触发通知。 我有一个单独的表,其中包含所有设备令牌。无法弄清楚如何准确地从表中获取每个设备令牌。 这是我到目前为止编写的firebase函数的一些代码sn-p,但没有运气。
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotificationToAllMembers = functions.database.ref('/chatRoom/{messageNode}').onWrite(event => {
const messageInfo = event.params.messageNode;
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/deviceTokens`).once('value');
// Get newly added Message detail
const getMovieMessageDetail = admin.database().ref(`/chatRoom/${messageInfo}`).once('value');
return Promise.all([getDeviceTokensPromise, getMovieMessageDetail]).then(results => {
const deviceTokensList = results[0];
const MessageDetail = results[1];
console.log('device tokens : ',deviceTokensList);
console.log('Fetched message detail', MessageDetail);
// Check if there are any device tokens.
if (!deviceTokensList.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', deviceTokensList.numChildren(), 'tokens to send notifications to.');
// Notification details.
const payload = {
notification: {
title: 'New Movie discussion',
body: `${MessageDetail.messageText}`,
}
};
// Listing all tokens.
const tokens = Object.keys(deviceTokensList.val());
// Send notifications to all tokens.
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(deviceTokensList.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
});
});
这是我所指的 firebase 实时数据库的快照, IE。每当“chatRoom”表中有推送时,我想向“deviceTokens”表中存在的每个设备令牌发送通知。
提前致谢!!
【问题讨论】:
-
你目前实现的代码有什么问题?
-
我遇到了同样的问题。它获取 -KvZ-vH8.... 而不是来自子 deviceToken 的值。它应该得到 fmGRCjoUwWG.... - 这些值,但它没有。
标签: android node.js firebase firebase-realtime-database firebase-cloud-messaging