云功能不会激活云消息

时间:2019-10-23 14:22:21

标签: firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions

我正在尝试从Firebase Cloud Functions激活Firebase Cloud消息。云功能似乎运行良好,功能日志中没有错误,但云消息未触发。我做了我能想到的一切,甚至确保Firebase实例ID正确且最新。

下面是代码

index.js

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}')
    .onWrite(async (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:', followedUid);

      // Get the list of device notification tokens.
      const getDeviceTokensPromise = admin.database()
          .ref(`/users/${followedUid}/notificationTokens`).once('value');

      console.log('We have notifications:', followerUid, 'for userz:', followedUid);

      // Get the follower profile.
      const getFollowerProfilePromise = admin.auth().getUser(followerUid);

            console.log('We getFollowerProfilePromise');

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

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

      const results = await Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]);
      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.
      const response = await admin.messaging().sendToDevice(tokens, payload);

      // 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());
          }
        }
              console.log('success');

      });
      return Promise.all(tokensToRemove);
    });

package.json

{
  "name": "fcm-notifications-functions",
  "description": "Send FCM notifications Firebase Functions sample",
  "dependencies": {
    "firebase-admin": "~7.1.1",
    "firebase-functions": "^2.2.1"
  },
  "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"
  },
  "engines": {
    "node": "8"
  },
  "private": true
}

0 个答案:

没有答案