【发布时间】:2017-12-31 21:03:09
【问题描述】:
我正在关注如何基于实时数据库触发器实现推送通知的 GitHub 代码。
这里是代码和链接:
https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/**
* Triggers when a user gets a new follower and sends a notification.
*
* Followers add a flag to `/followers/{followedUid}/{followerUid}`.
* Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`.
*/
exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event => {
const followerUid = event.params.followerUid;
const followedUid = event.params.followedUid;
// If un-follow we exit the function.
if (!event.data.val()) {
return console.log('User ', followerUid, 'un-followed user', followedUid);
}
console.log('We have a new follower UID:', followerUid, 'for user:', followerUid);
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');
// Get the follower profile.
const getFollowerProfilePromise = admin.auth().getUser(followerUid);
return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const follower = 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: 'You have a new follower!',
body: `${follower.displayName} is now following you.`,
icon: follower.photoURL
}
};
// 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);
});
});
});
我的愚蠢问题是 Functions 和 Node 的新手,在此代码中通知会发送给所有保存令牌的用户,对吗?如果是这样,我怎么能说只发送给一个特定的人而不是全部?
我正在考虑将每个用户的令牌保存在不同的节点(子节点)中,以便我可以选择要发送通知的那个。有用吗?
谢谢大家
【问题讨论】:
-
可以通过 FCM 向单个用户发送通知,这可以通过 Cloud Functions 完成。如果您是 JavaScript 新手,Cloud Functions 示例并不是学习它的最佳方式。我建议首先阅读用于发送消息的FCM Admin SDK 的文档。 Codelab for web developers 和 Cloud Functions codelab 也值得一试。
-
嗨弗兰克,谢谢。我看了他们一些不适用于我的目的。我正在尝试发送基于实时数据库的通知。我看到的问题是,包括您发布的问题,它需要所有设备的所有令牌并为所有用户发送通知。我想为一个用户做这件事。
-
为了向单个用户发送通知,您需要修改代码以仅读取该用户的令牌。您在现有示例代码和预期结果之间没有显示任何步骤,因此我假设您很难开始。因此,我提出了一些材料来帮助您更熟悉 Firebase 数据库和 FCM。例如。 web codelab 展示了如何从数据库中读取数据。
标签: ios node.js firebase firebase-cloud-messaging