【问题标题】:Firebase cloud function send notificationsFirebase 云功能发送通知
【发布时间】:2019-02-23 13:23:30
【问题描述】:

部署云功能并在我的代码中使用 async / await 时会出现此错误。这里有什么问题?

 // Import the Firebase SDK for Google Cloud Functions.
const functions = require('firebase-functions');
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
// admin.initializeApp();
admin.initializeApp(functions.config().firebase);




exports.addWelcomeMessages = functions.auth.user().onCreate(async(user)=> {
  console.log('A new user signed in for the first time.'+user.displayName);
  const fullName = user.displayName || 'Anonymous';

      // Saves the new welcome message into the database
      // which then displays it in the FriendlyChat clients.
      return admin.database().ref('messages').push({
        name: 'Firebase Bot',
        profilePicUrl: '/images/firebase-logo.png', // Firebase logo
        text: `${fullName} signed in for the first time! Welcome!`,
      });
      // console.log('Welcome message written to database.');
});


    exports.sendNotifications = functions.database.ref('/messages/{messageId}').onCreate(async(snapshot) => {
          // Notification details.
          const text = snapshot.val().text;
          const payload = {
            notification: {
              title: `${snapshot.val().name} posted ${text ? 'a message' : 'an image'}`,
              body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
              icon: snapshot.val().photoUrl || '/images/profile_placeholder.png',
              click_action: `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com`,
            }
          };

                // // Get the list of device tokens.
                const allTokens = await admin.database().ref('fcmTokens').once('value');
                if (allTokens.exists()) {
                  // Listing all device tokens to send a notification to.
                  const tokens = Object.keys(allTokens.val());
                  // Send notifications to all tokens.
                  const response = await admin.messaging().sendToDevice(tokens, payload);
                  await cleanupTokens(response, tokens);
            console.log('Notifications have been sent and tokens cleaned up.');
          }
        });


        // Cleans up the tokens that are no longer valid.
    function cleanupTokens(response, tokens) {
     // For each notification we 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[`/fcmTokens/${tokens[index]}`] = null;
         }
       }
     });
     return admin.database().ref().update(tokensToRemove);
    }

【问题讨论】:

  • 发送通知方法中的语法错误,我猜你错过了关闭括号。
  • 我只是在我的代码中加入了 async /await 词然后给我这个错误。
  • 请在此处添加您的代码
  • 我把它从 Cloud Functions for Firebase 代码实验室复制过来
  • @eslammahmoud 请从答案中删除您的代码

标签: javascript firebase google-cloud-functions


【解决方案1】:

我的第一个猜测是您没有使用节点 8,因此您的代码正在为较旧的运行时进行解析(不支持 async/await

见:

【讨论】:

  • 我用的是节点 8,我检查一下。
  • 我已经解决了,只需在 package.json 文件中添加 "engines": { "node": "8" },
猜你喜欢
  • 2021-04-04
  • 2018-06-01
  • 1970-01-01
  • 2021-03-08
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-12-18
  • 2020-09-09
相关资源
最近更新 更多