【发布时间】:2018-07-22 04:49:20
【问题描述】:
我想监视每个用户的通知树何时更改,并向他们发送通知。通知有一个动作和用户名,这是通知唯一需要的东西
在配置 firebase 工具后,我正在使用 nodejs 和 npm,我已将此文件部署到我的 firebase 控制台。不,我这辈子都没用过 js
let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = .
functions.database.ref('/users/{uid}/notifications').onWrite((event)
=> {
const uid = event.params.uid
if (!event.data.val()){
return console.log('User' , uid)
}
const getDeviceTokensPromise =
admin.database().ref(`/users/${uid}/notificationToken`).once('value');
const getUserWithUid = admin.auth().getUser(uid);
return Promise.all([getDeviceTokensPromise, getUserWithUid]).then((results) => {
const tokensSnapshot = results[0];
const user = 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', follower);
// Notification details.
const payload = {
notification: {
title: `${user.username}`,
body: `${user.action} `,
},
};
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.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(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
});
这是我的数据库的屏幕截图:
这是我如何获得存储在 FB 中的“notificationToken”值:
(Messaging.messaging().fcmToken)!
我如何订阅通知:
messaging.subscribe(toTopic: "users/\(uid)/notifications")
谁能告诉我我做错了什么?
这是日志的屏幕截图:
【问题讨论】:
-
代码有什么问题?你的云函数被触发了吗?它是否正确地从数据库加载令牌?日志中是否显示任何错误?你试过triggering it in the Cloud Functions emulator 看看会发生什么吗?
-
@FrankvanPuffelen 看到我的编辑,干杯伙伴不确定它是否正确加载令牌或者我是否使用正确的令牌更清楚,云功能没有被触发并且通知没有被发送或收到
标签: node.js firebase firebase-realtime-database firebase-cloud-messaging firebase-admin