Firebase云功能和FCM:如何将设备发送到设备消息? (JavaScript,Swift 3)

时间:2017-08-03 21:31:23

标签: javascript firebase push-notification firebase-cloud-messaging google-cloud-functions

我正在尝试使用云功能将设备发送到Firebase中的设备消息。我以前从未在JavaScript中编码,并且正在使用此GitHub页面中的模板:https://github.com/firebase/functions-samples/tree/master/fcm-notifications。这已在官方文档中推荐。但是,我试图重写代码以使其符合我在聊天应用程序中的需求。

我在做什么以及该功能应该做什么?

  • 我将设备令牌从FIRInstanceID保存到数据库,以便从云功能中轻松检索
  • 我将带有text,receiverID和senderUserName的任何新邮件上传到数据库中的专用路径
  • 云功能会观察此数据库路径,并在每次有人上传新通知时调用
  • 云功能获取数据并在检索到设备令牌后通知给属于接收者ID的用户

这是我目前的云功能:

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

exports.sendFollowerNotification = functions.database.ref('/notifications/notificationsToBeProcessed').onWrite(event => {
  const data = event.data.val();
  const text = data["text"];
  const receiverID = data["receiverID"];
  const senderUserName = data["senderUserName"];

  const payload = {
    notification: {
      title: 'Hey!',
      body: text
    }
  };

  var rootRef = firebase.database().ref('/notification-tokens/{receiverID}');
  rootRef.once("value")
    .then(function(snapshot) {

      var token = snapshot.child("{receiverID}")

      return admin.messaging().sendToDevice(token, 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());
            }
          }
        });
      });

    });

  })

})

我尝试部署时遇到此错误:

SyntaxError: Unexpected token }
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /Users/jonas/.npm-global/lib/node_modules/firebase-tools/lib/triggerParser.js:18:11

有一点JavaScript经验的人能告诉我我的错误在哪里吗?谢谢!

0 个答案:

没有答案