Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Cloud Firestore from a Cloud Function?

I'm trying to retrieve data from my Cloud Firestore to eventually use in a GraphQL server, but for now I'm just returning JSON to test. I'm using the following code to access Firestore, but don't seem to be getting any data back. I know the function works correctly since the "start test" and "final test push" appears as expected in the JSON response.

I've tried using the Admin SDK instructions as well, to no avail. Can anyone spot what I'm doing wrong here?

import * as admin from "firebase-admin"
import * as functions from "firebase-functions"

admin.initializeApp(functions.config().firebase)
const db = admin.firestore()

const authors = [{ key: "start test" }]
db.collection("authors")
    .get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            const data = {
                id: doc.id,
                firstName: doc.firstName,
                lastName: doc.lastName
            }
            authors.push(data)
            authors.push({ key: "test in loop" })
        })
    })
authors.push({ key: "final test push" })

export default authors

Thanks a lot!

EDIT: I should note that this is from a separate getter file. The Cloud Function itself is elsewhere and is working properly.

EDIT #2: Cloud function definition

import authorsArray from "./firestore"

const testServer = express()
testServer.get("*", (req, res) => {
    res.setHeader("Content-Type", "application/json")
    res.send(JSON.stringify({ data: authorsArray }))
})
const test = https.onRequest(testServer)
like image 930
Nico Avatar asked Jan 13 '18 15:01

Nico


People also ask

How Firebase Cloud Functions work?

Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your JavaScript or TypeScript code is stored in Google's cloud and runs in a managed environment.

How does Google Cloud Functions work?

Google Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your function is triggered when an event being watched is fired.


1 Answers

Try to change the code as follow; As snapshot data is doc.data() and id is doc.id

db.collection("authors")
    .get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            const data = {
                id: doc.id,
                firstName: doc.data().firstName,
                lastName: doc.data().lastName
            }
            authors.push(data)
            authors.push({ key: "test in loop" })
        })

for your reference check the link

like image 142
HakanC Avatar answered Nov 02 '22 01:11

HakanC