在Firebase云功能中发送推送通知时出错

时间:2020-05-22 12:02:31

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

我正在尝试使用Firebase云功能创建推送通知。以下是我的代码:

const admin = firebase
exports.sendNewTripNotification = functions.firestore
  .document('notifications/{notificationId}')
  .onWrite(async (event) => {
    console.log("event: ", event)
    const key = "cK0e5ZRAVRUAlx8hXHkNkXp7mj43"
    const ref = admin.database().ref(`users/${key}/deviceToken`);
    console.log("ref: ", ref)
    const deviceToken = admin.database().ref(`/users/${key}/deviceToken`).once('value');
    return deviceToken.then(result => {
      const token_id = result.val();
      console.log("token_id", token_id)
      const payload = {
        notification: {
          title: "Friend Request",
          body: "You just got a new friend request",
          icon: "default"
        }
      };
      console.log("payload", payload)
      return admin.messaging().sendToDevice(token_id, payload).then(Response => {
        console.log('this is the notification',Response)
      });
    });
  })

我遇到以下错误:

错误:提供给sendToDevice()的注册令牌必须是 非空字符串或非空数组。 在FirebaseMessagingError.FirebaseError [作为构造函数](/srv/node_modules/firebase-admin/lib/utils/error.js:42:28) 在FirebaseMessagingError.PrefixedFirebaseError [作为构造函数](/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)

我确实参考了以下两个链接,但没有任何帮助。我在这里做错什么了吗?

Firebase Cloud Functions get data on real time database onCreate

Firebase Cloud Functions Tokens

2 个答案:

答案 0 :(得分:0)

您正在将async / await与then()混合使用,不建议这样做。以下应该可以解决问题(未试用):

exports.sendNewTripNotification = functions.firestore
    .document('notifications/{notificationId}')
    .onWrite(async (event) => {
        console.log("event: ", event)

        const key = "cK0e5ZRAVRUAlx8hXHkNkXp7mj43"
        const ref = admin.database().ref(`users/${key}/deviceToken`);
        console.log("ref: ", ref)

        const deviceToken = await ref.once('value');
        const token_id = deviceToken.val();

        console.log("token_id", token_id)

        const payload = {
            notification: {
                title: "Friend Request",
                body: "You just got a new friend request",
                icon: "default"
            }
        };

        const messagingDevicesResponse = await admin.messaging().sendToDevice(token_id, payload);

        console.log('this is the notification', messagingDevicesResponse)

        return null;

    })

答案 1 :(得分:0)

问题已解决。我犯了一个愚蠢的错误。在另一个设备上登录时,我并没有覆盖设备令牌。