Firebase云功能发送通知

时间:2018-09-19 11:19:02

标签: javascript firebase google-cloud-functions

在部署云功能并在我的代码中使用async / await时显示此错误。这是什么问题?

https://i.stack.imgur.com/kR6Es.png

 // 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);
    }

1 个答案:

答案 0 :(得分:0)

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

请参阅: