【发布时间】:2018-06-02 11:49:54
【问题描述】:
我有带有 Firebase 数据库和 Firebase 云消息传递的聊天应用程序。我可以通过控制台发送 firebase 通知,但在实际情况下它应该是自动的。为了自动通知,我的朋友为我写了Index.js(添加在云功能中)文件,但它不发送通知。
根据我们的逻辑函数,只要有任何新条目(在任何节点或任何房间),就应该触发,并通过 firebase 函数获取这些值并向 FCM 服务器发出发布请求以通知接收器设备(获取接收器的值设备从 token_To)。
- 留言
- Message_From
- 时间
- 类型
- token_To
Index.js
var functions = require('firebase-functions');
var admin = require('firebase-admin');
var serviceAccount = require('./demofcm-78aad-firebase-adminsdk-4v1ot-2764e7b580.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://demofcm-78aad.firebaseio.com/"
})
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
exports.setUserNode = functions.auth.user().onCreate(event => {
// ...
});
exports.notifyMsg = functions.database.ref('/{chatroom}/{mid}/')
.onWrite(event => {
if (!event.data.val()) {
return console.log('Message Deleted');
}
const getDeviceTokensPromise = admin.database().ref('/{chatroom}/{mid}/token_to').once('value');
return Promise.all([getDeviceTokensPromise]).then(results => {
const tokensSnapshot = results[0];
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
const payload = {
notification: {
title: 'You have a new Message!',
body: event.data.val().Message
}
};
const tokens = Object.keys(tokensSnapshot.val());
return admin.messaging().sendToDevice(tokens, payload).then(response => {
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
});
});
Firebase 函数日志
如何从数据库中获取同一房间(9810012321-9810012347)或任何其他房间(9810012321-9810012325)中任何新添加节点的上述值并将其发送到 FCM 以进行通知
提前致谢。
【问题讨论】:
标签: javascript android node.js firebase firebase-realtime-database