簡體   English   中英

如何在 typescript 編寫的谷歌雲 Function 中檢索和使用 firebase 數據?

[英]How can I retrieve and use firebase data in a Google Cloud Function written in typescript?

問題

我有一份關於 Firebase 的文檔,其存儲結構如下所示。

從 typescript 中編寫的谷歌雲Function中,我想訪問和使用存儲在我的 Firebase 項目中的 JSON 數據。 我不確定要使用的正確語法。

Firebase 文檔結構:

"users": {
    "tim": {
        "score": 1200
         "health": 200
         "items": {
            123123,
            182281,
            123344,
         }
     }
    "james": {
        "score": 100
         "health": 50
         "items": {
            143553,
            567454,
         }
     }
}

我目前使用以下代碼從 Firebase 檢索數據。

import * as admin from "firebase-admin";

export class ScoreHandler {
    constructor(private firestore: FirebaseFirestore.Firestore) {}

async calculateFinalScore(name: string): Promise<number> {
    try{
        const document = await this.firestore
          .collection("users")
          .doc("users")
          .get();
        
        // Check if record exists
        if (document.data() === undefined) {
           throw console.warn("unable to find users document data);
        }
        
        //!!THIS IS WRONG!! not sure how to read in and access this data?
        const score: number = document.data()["users"]["tim"]["score"];
        const health: number = document.data()["users"]["tim"]["health"];
        const items: Array<number> = document.data()["users"]["tim"]["items"];

        //Calculate Final score using score, health and items
        const finalScore: number = score * health * items.length;
        return finalScore;
        
    } catch (e) {
        // Log the Error on the Console
        console.error(e);
        return 0.0;
    }
    
}

我不確定從 Typescript 中的文檔快照訪問數據的正確語法。我希望能夠從我的 firebase 項目中獲取分數、健康狀況和項目數組到我的雲 function class 中。

任何幫助是極大的贊賞。
謝謝!

我試圖獲取數據,但一直收到 object is possibly undefined errors 並且無法實際獲取數據。

要訪問數據,您可以在快照 object 上使用data()方法。此方法將文檔中的數據返回為 object。

您正在使用data()方法獲取文檔快照中的數據,但您沒有使用正確的屬性名稱來訪問數據。 data()方法返回一個 object,而不是 JSON object。因此,您需要為 object 使用正確的屬性名稱。

嘗試像這樣訪問 tim object 的 score 屬性:

const score: number = document.data()["users"]["tim"]["score"];

訪問 data() 方法返回的 JavaScript object 中的得分屬性的正確方法如下所示:

const score: number = document.data()["tim"]["score"];

要訪問時間 object 中的其他屬性,您可以使用以下語法:

const health: number = document.data()["tim"]["health"];
const items: Array<number> = document.data()["tim"]["items"];

以下是您的calculateFinalScore()方法應該如何使用正確的語法來訪問 Firestore 文檔快照中的數據:

async calculateFinalScore(name: string): Promise<number> {
  try{
    const document = await this.firestore
      .collection("users")
      .doc("users")
      .get();

    // Check if record exists
    if (document.data() === undefined) {
      throw console.warn("unable to find users document data");
    }

    // Get the score, health and items from the document snapshot
    const score: number = document.data()["tim"]["score"];
    const health: number = document.data()["tim"]["health"];
    const items: Array<number> = document.data()["tim"]["items"];

    // Calculate Final score using score, health and items
    const finalScore: number = score * health * items.length;
    return finalScore;
  } catch (e) {
    // Log the Error on the Console
    console.error(e);
    return 0.0;
  }
}

用戶名被硬編碼為“tim”。 如果要訪問不同用戶的數據,則需要將“tim”屬性名稱替換為要訪問的用戶的名稱。 像:

const score: number = document.data()["james"]["score"];
const health: number = document.data()["james"]["health"];
const items: Array<number> = document.data()["james"]["items"];

暫無
暫無

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

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