简体   繁体   中英

Using Firebase cloud functions callable

I am trying to use the admin sdk to check for a user phone number. when i check for a number in the database, it displays the result, but when i input a number not in the database, it throws an internal error.

below is a sample code of the functions index.js

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

          exports.checkPhoneNumber = functions.https.onCall(async (data, context) => {
            const phoneNumber = await admin.auth().getUserByPhoneNumber(data.phoneNumber);
            return phoneNumber;
          })

front-end.js

          toPress = () => {
            const getNumberInText = '+12321123232';

            const checkPhone = Firebase.functions.httpsCallable('checkPhoneNumber');
            checkPhone({ phoneNumber: getNumberInText }).then((result) => {
              console.log(result);
            }).catch((error) => {
              console.log(error);
            });
          }

below is the error i am getting when i input a number thats not in the auth

- node_modules\@firebase\functions\dist\index.cjs.js:59:32 in HttpsErrorImpl
- node_modules\@firebase\functions\dist\index.cjs.js:155:30 in _errorForResponse

- ... 14 more stack frames from framework internals

As you will read in the documentation of Callable Cloud Functions:

The client receives an error if the server threw an error or if the resulting promise was rejected.

If the error returned by the function is of type function.https.HttpsError , then the client receives the error code, message, and details from the server error. Otherwise , the error contains the message INTERNAL and the code INTERNAL .

Since you don't specifically manage errors in your Callable Cloud Function, you receive an INTERNAL error.


So, if you want to get more details in your front-end, you need to handle the errors in your Cloud Function, as explained here in the doc.

For example, you could modify it as follows:

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

    try {
        const phoneNumber = await admin.auth().getUserByPhoneNumber(data.phoneNumber);
        return phoneNumber;
    } catch (error) {
        console.log(error.code);
        if (error.code === 'auth/invalid-phone-number') {
            throw new functions.https.HttpsError('not-found', 'No user found for this phone number');
        }
    }
})

We throw an error of type not-found (See all the possible Firebase Functions status codes here ) in case the error code returned by the getUserByPhoneNumber() method is auth/invalid-phone-number (See all the possible error codes here ).

You could refine this error handling code, by treating other errors returned by getUserByPhoneNumber() and sending to the client other specific status codes.

Here is a way I usually use to check if a field (ex. phone) exists in any of the documents in my collection.

For an example based on what you described here is a collection I have created:

在此处输入图片说明

The code to make a query for checking if a phone exists looks like this: (I'm using Node.Js)

let collref = db.collection('posts');

var phoneToCheck = '+123456789'
const phone1 = collref.where('phone', '==', phoneToCheck)

let query1 = phone1.get()
  .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }

    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
    });
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });

If a Document exists with that phone number the response is like this:

在此处输入图片说明

I no document has that phone number then the response is the following:

在此处输入图片说明

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