简体   繁体   中英

Firebase cloud function send notifications

This error shows when deploying cloud functions and use async / await in my code. what is the problem here?

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

My first guess is that you're not using node 8, so your code is being parsed for the older runtime (which doesn't support async / await .

See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM