简体   繁体   中英

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

Problem

I have a document on Firebase stored with the following structure seen below.

From a Google Cloud Function written in typescript , I would like to access and use the JSON data stored in my Firebase project. I am unsure of the correct syntax to use.

Firebase Document structure:

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

I currently retrieve the data from Firebase using the following code.

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

I am unsure of the correct syntax to access data from a document snapshot in Typescript. I would like to be able to get the score, health and array of items from my firebase project into my cloud function class.

Any help is greatly Appreciated.
Thanks!

I have tried to get the data but keep getting object is possibly undefined errors and am unable to actually get the data.

To access the data you can use the data() method on the snapshot object. This method returns the data in the document as an object.

You are using the data() method to get the data in the document snapshot, but you are not using the correct property names to access the data. The data() method returns an object, not a JSON object. Therefore, you need to use the correct property names for the object.

Try to access the score property of the tim object like this:

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

The correct way to access the score property in the JavaScript object returned by the data() method would look like this:

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

To access the other properties in the tim object, you would use the following syntax:

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

Here is how your calculateFinalScore() method should look like using the correct syntax to access the data in the Firestore document snapshot:

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

The name of the user is hardcoded as "tim". If you want to access the data for a different user, you will need to replace the "tim" property name with the name of the user that you want to access. Like:

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

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