Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

firebase - 错误:无法加载默认凭据。 -云功能(Error: Could not load the default credentials. - Cloud Functions)

I'm working on the group functionality for my react-native app.

(我正在为我的react-native应用程序进行分组功能。)

And I wish to send cloud messages to users who have been added when a group is created.

(我希望将云消息发送给创建组时已添加的用户。)

I'm using cloud functions to do that.

(我正在使用云功能来做到这一点。)

But I am getting this error in my function:

(但是我的函数出现此错误:)

Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

在此处输入图片说明

Its unable to fetch the fcm-token from firestore to send the notification.

(它无法从Firestore获取fcm令牌来发送通知。)

I had written cloud functions for sending friend requests and in that, the token is retrieved successfully from cloud firestore, and the notification is sent.

(我编写了用于发送朋友请求的云函数,其中,从云Firestore成功检索了令牌,并发送了通知。)

This is my cloud function :

(这是我的云功能:)


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

//======================NOTIFY ADDED MEMBERS==========================//

exports.notifyAddedMembers = functions.https.onCall((data, context) => {
  const members = data.members;
  const groupName = data.groupName;
  var tokens = [];
  members.forEach(async member => {
    //send notifications to member.uid
    console.log('MEMBER.UID ', member.uid);
    await fetchTokenFromUid(member.uid)
      .then(token => {
        console.log('retrieved token: ', token);
        // tokens.push(token);
        const payload = {
          notification: {
            title: `You have been added to ${groupName}`,
            body: 'Share your tasks',
            sound: 'default',
          },
        };
        return admin.messaging().sendToDevice(token, payload);
      })
      .catch(err => console.log('err getting token', err));
  });
  // console.log('ALL TOKENS: ', tokens);
  console.log('GROUP NAME: ', groupName);
});

async function fetchTokenFromUid(uid) {
  var token = '';
  return await admin
    .firestore()
    .collection('Users')
    .doc(`${uid}`)
    .get()
    .then(async doc => {
      console.log('uid token: ', Object.keys(doc.data().fcmTokens));
      var tokenArray = Object.keys(doc.data().fcmTokens); //ARRAY
      for (var i = 0; i < tokenArray.length; i++) {
        token = tokenArray[i]; //Coverts array to string
      }
      return token; //return token as string
    });
}

I am using the react-native-firebase library.

(我正在使用react-native-firebase库。)

  ask by yashatreya translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are correctly loading the firebase-functions and firebase-admin modules, and initializing an admin app instance.

(您正在正确加载firebase-functionsfirebase-admin模块,并初始化admin应用程序实例。)

I don't know what exactly generates the error you got, but based on this SO Question it could be because, in your Cloud Function, you are mixing the use of async/await with the then() method.

(我不知道到底是什么导致了错误,但是基于这个SO问题 ,可能是因为在您的Cloud Function中,您正在将async/await使用与then()方法混合使用。)

Do you have any other Cloud Function(s) in your index.js file?

(您的index.js文件中是否还有其他Cloud Function?)

In particular some that interact with other Google APIs.

(特别是与其他Google API交互的一些API。)

I propose to refactor your code as follows, using Promise.all() .

(我建议使用Promise.all()如下重构您的代码。)

You first fetch all the tokens and then you send the messages.

(您首先获取所有令牌,然后发送消息。)

exports.notifyAddedMembers = functions.https.onCall(async (data, context) => {

    try {
        const members = data.members;
        const groupName = data.groupName;

        const promises = [];
        members.forEach(member => {
            promises.push(admin
                .firestore()
                .collection('Users')
                .doc(member.uid).get());
        });

        const tokensSnapshotsArray = await Promise.all(promises);

        const promises1 = [];
        tokensSnapshotsArray.forEach(snap => {

            const token = snap.data().fcmToken;  //Here you may adapt as it seems you have an array of tokens. I let you write the loop, etc.

            const payload = {
                notification: {
                    title: `You have been added to ${groupName}`,
                    body: 'Share your tasks',
                    sound: 'default',
                },
            };
            promises1.push(admin.messaging().sendToDevice(token, payload));

        });

        await Promise.all(promises1);

        return { result: 'OK' }
    } catch (error) {
        //See the doc: https://firebase.google.com/docs/functions/callable#handle_errors
    }

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...