簡體   English   中英

使用可調用的 Firebase 雲函數

[英]Using Firebase cloud functions callable

我正在嘗試使用 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;
          })

前端.js

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

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

下面是當我輸入一個不在 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

正如您將在 Callable Cloud Functions 的文檔中讀到的:

如果服務器拋出錯誤或結果承諾被拒絕,則客戶端會收到錯誤。

如果該函數返回的錯誤類型為function.https.HttpsError ,則客戶端會收到來自服務器錯誤的錯誤代碼、消息和詳細信息。 否則,錯誤包含消息INTERNAL和代碼INTERNAL

由於您沒有專門管理 Callable Cloud Function 中的錯誤,因此您會收到 INTERNAL 錯誤。


所以,如果你想在你的前端更多的細節,你需要處理你的雲功能的錯誤,說明這里的文檔。

例如,您可以按如下方式修改它:

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

如果getUserByPhoneNumber()方法返回的錯誤代碼是auth/invalid-phone-number (請在此處查看所有可能的錯誤代碼),我們會拋出not-found類型的錯誤(請在此處查看所有可能的 Firebase 函數狀態代碼)。

您可以通過處理getUserByPhoneNumber()返回的其他錯誤並向客戶端發送其他特定狀態代碼來優化此錯誤處理代碼。

這是我通常用來檢查我的集合中的任何文檔中是否存在字段(例如電話)的方法。

對於基於您在此處描述的內容的示例,我創建了一個集合:

在此處輸入圖片說明

進行查詢以檢查電話是否存在的代碼如下所示:(我使用的是 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);
  });

如果存在具有該電話號碼的文檔,則響應如下:

在此處輸入圖片說明

我沒有文件有那個電話號碼,然后回復如下:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM