使用可调用的Firebase云功能

时间:2019-12-30 07:22:03

标签: node.js reactjs firebase react-native google-cloud-functions

我正在尝试使用admin sdk检查用户电话号码。当我检查数据库中的数字时,它会显示结果,但是当我在数据库中未输入数字时,它将引发内部错误。

下面是函数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);
            });
          }

以下是我在身份验证中输入的数字以外的错误

    HttpsErrorImpl中的
  • node_modules @ firebase \ functions \ dist \ index.cjs.js:59:32
  • _errorForResponse中的
  • node_modules @ firebase \ functions \ dist \ index.cjs.js:155:30

  • ...更多来自框架内部的14个堆栈框架

2 个答案:

答案 0 :(得分:1)

您将在documentation中阅读可调用云函数:

  

如果服务器抛出错误或所产生的承诺被拒绝,则客户端会收到错误消息。

     

如果函数返回的错误的类型为function.https.HttpsError,则客户端将从服务器错误中接收错误代码,消息和详细信息。 否则,该错误包含消息INTERNAL和代码INTERNAL

由于您没有专门管理Callable Cloud Function中的错误,因此会收到内部错误。


因此,如果您想在前端获得更多详细信息,则需要处理Cloud Function中的错误,如文档中的here所述。

例如,您可以对其进行如下修改:

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

如果here方法返回的错误代码为not-found(如果抛出auth/invalid-phone-number类型的错误(请参阅所有可能的Firebase功能状态代码getUserByPhoneNumber())(查看所有可能的错误代码here)。

您可以通过处理getUserByPhoneNumber()返回的其他错误并将其他特定状态代码发送给客户端来完善此错误处理代码。

答案 1 :(得分:0)

这是我通常用来检查集合中任何文档中是否存在字段(例如电话)的一种方法。

基于您在此描述的示例是我创建的一个集合:

enter image description here

用于查询电话是否存在的查询代码如下:(我正在使用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);
  });

如果文档中包含该电话号码,则响应如下:

enter image description here

我没有文件有该电话号码,那么响应如下:

enter image description here