在Firebase实时数据库中添加新节点时,使用云功能发送推送通知? [英] Sending push notification using cloud function when a new node is added in firebase realtime database?

查看:140
本文介绍了在Firebase实时数据库中添加新节点时,使用云功能发送推送通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在消息"节点中添加子项时发送通知

Sending notification when a child is added in Message node

每当在Message节点中添加新子级时,所有用户都应该收到诸如您有新消息"之类的消息.我对node.js不太了解,因此我希望云功能能够发送通知.

Whenever new child is added in Message node all the users should get message like"You have new message".I don't know much about node.js so I want cloud function that will send notification.

推荐答案

此后,您会找到指向满足您需求的教程或代码示例的链接. (更新:我还复制了第一个示例的完整代码,这是Firebase的官方示例).

You will find hereafter links to tutorials or code examples covering your needs. (Update: I also copied the entire code of the first example, which is an official Firebase sample).

https://firebase.google.com/docs/functions/use -cases#notify_users_when_something_interesting_happens

https://github.com /firebase/functions-samples/blob/master/developer-motivator/functions/index.js

https://android.jlelse.eu /serverless-notifications-with-cloud-functions-for-firebase-685d7c327cd4

更新:在评论之后,我将第一个示例(这是Firebase的官方示例)的源代码粘贴下方.

UPDATE: Following the comment, I paste below the source from the first example (which is an official Firebase sample).

使用Firebase Admin SDK发送通知.网路 客户端将各个设备令牌写入实时数据库 函数用于发送通知的

Sending the notification is done using the Firebase Admin SDK. The Web client writes the individual device tokens to the realtime database which the Function uses to send the notification.

依赖关系列在functions/package.json中.

The dependencies are listed in functions/package.json.

示例数据库结构

用户登录该应用,并被要求启用有关以下内容的通知 他们的浏览器.如果他们成功启用了通知,则设备 令牌保存到以下位置的数据存储中 /users/$ uid/notificationTokens.:

Users sign into the app and are requested to enable notifications on their browsers. If they successfully enable notifications the device token is saved into the datastore under /users/$uid/notificationTokens.:

/functions-project-12345
    /users
        /Uid-12345
            displayName: "Bob Dole"
            /notificationTokens
                1234567890: true
            photoURL: "https://lh3.googleusercontent.com/..."

如果一个用户开始关注另一个用户,我们将写信给 /followers/$ followedUid/$ followerUid:

If a user starts following another user we'll write to /followers/$followedUid/$followerUid:

/functions-project-12345
    /followers
        /followedUid-12345
            followerUid-67890: true
    /users
        /Uid-12345
            displayName: "Bob Dole"
            /notificationTokens
                1234567890: true
            photoURL: "https://lh3.googleusercontent.com/..."

触发规则

该函数每次在以下位置更改跟随标志的值时触发 /followers/$ followedUid/$ followerUid.

The function triggers every time the value of a follow flag changes at /followers/$followedUid/$followerUid.

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();

/**
 * 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((change, context) => {
      const followerUid = context.params.followerUid;
      const followedUid = context.params.followedUid;
      // If un-follow we exit the function.
      if (!change.after.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);

      // The snapshot to the user's tokens.
      let tokensSnapshot;

      // The array containing all the user's tokens.
      let tokens;

      return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
        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 as an array.
        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);
      });
});

package.json

{
  "name": "fcm-notifications-functions",
  "description": "Send FCM notifications Firebase Functions sample",
  "dependencies": {
    "firebase-admin": "~5.11.0",
    "firebase-functions": "^1.0.0"
  },
  "devDependencies": {
    "eslint": "^4.13.1",
    "eslint-plugin-promise": "^3.6.0"
  },
  "scripts": {
    "lint": "./node_modules/.bin/eslint --max-warnings=0 .",
    "serve": "firebase serve --only functions",
    "shell": "firebase experimental:functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "private": true
}

这篇关于在Firebase实时数据库中添加新节点时,使用云功能发送推送通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆