javascript - Firebase Cloud Functions 与 Cloud Firestore 出现问题

标签 javascript node.js google-cloud-functions google-cloud-firestore

我在之前的项目中使用过此 Firebase 数据库代码:

const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value');

我现在正在尝试将其转换为 Firestore。我基本上是想在发送通知时获取用户的 fcm。我尝试了很多事情,但还没有看到实现这一目标的新方法。

编辑:这是我的代码。

exports.sendFavoriteNotification = functions.firestore.document('users/{userUid}/notifications/{notificationId}').onCreate(event => {
const notification = event.data.data();
const user = event.params.userUid;

const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value');

// Get the follower profile.
const getProfilePromise = admin.auth().getUser(notification.sender);

return Promise.all([getDeviceUser, getProfilePromise]).then(results => {
  const tokensSnapshot = results[0];
  const liker = 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', liker);

  // Notification details.
  const payload = {
    notification : {
      title : 'You have a new like!',
      body : `${liker.displayName} just liked your photo.`,
      badge: '1',
      sound: 'default'
    }
  };

  // Listing all tokens.
  var tokens = admin.firestore.ref(`/users/${notification.to}/`).get('fcm');

  // Send notifications to all tokens.
  admin.messaging().sendToDevice(tokens.data(), payload);
  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.update({
            fcm: FieldValue.delete()
          }));
        }
      }
    });
    return Promise.all(tokensToRemove);
  });
});

});

最佳答案

希望这会有所帮助。这是我经过 2 天尝试学习如何从实时数据库转换为 firestore 后的代码。它基于 firebase 项目:https://github.com/MahmoudAlyuDeen/FirebaseIM

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


exports.sendNotificationToFirestone = functions.firestore.document('/notifications/{pushId}')
    .onCreate(event => {
        const pushId = event.data.id;
        const message = event.data.data();
        const senderUid = message.from;
        const receiverUid = message.to;
        const db = admin.firestore();

        if (senderUid === receiverUid) {
            console.log('pushId: '+ pushId);
            return db.collection('notifications').doc(pushId).delete();;
        } else {
            const ref = db.collection('users').doc(receiverUid);

            const query = new Promise(
                function (resolve, reject) {
                    ref.get()
                        .then(doc => {
                            if (!doc.exists) {
                                console.log('No such document!');
                                reject(new Error('No such document!'));

                            } else {
                                console.log('Document data:', doc.data().instanceId);
                                resolve(doc.data().instanceId);
                            }
                        })
                        .catch(err => {
                            console.log('Error getting document', err);
                            reject(err);
                        });
                });


            const getSenderUidPromise = admin.auth().getUser(senderUid);

            return Promise.all([query, getSenderUidPromise]).then(results => {
                //console.log('instanceId = Result[0]: ' + results[0]);
                //console.log('sender = Result[1]: ' + results[1]);
                const instanceId = results[0];
                const sender = results[1];
                //console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);
                //console.log('instanceId este' + instanceId);

                const payload = {
                    notification: {
                        title: sender.displayName,
                        body: message.body,
                        icon: sender.photoURL
                    }
                };

                admin.messaging().sendToDevice(instanceId, payload)
                    .then(function (response) {
                        console.log("Message sent: ", response);
                    })
                    .catch(function (error) {
                        console.log("Error sending message: ", error);
                    });
            });
        }
    });

关于javascript - Firebase Cloud Functions 与 Cloud Firestore 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47039196/

相关文章:

javascript - 将 Javascript 日期转换为带有时区信息的 UTC

javascript - 如何使用 materializecss 框架使 Accordion 在悬停时展开而不是在单击时展开

javascript - 尝试在异步云函数( Node v8)中执行 fs.writefile()

javascript - Ember 中的观察者功能?

javascript - 有缺陷的二叉树

node.js - 没有可用的 Nodejs 包。 Elastic Beanstalk 上的错误 : Nothing to do. Rails 应用程序

node.js - 从工件中删除旧文件后无法部署云功能

node.js - 每个 then() 应该返回一个值或抛出,promise/always-return

node.js - 在哪里使用 Neo4j

node.js - 如果中间件在 REST API 中失败,会有什么响应?