Reputation: 446
I use the Firebase Emulator Suite to run and debug my Cload Functions locally, as described in this guide: https://firebase.google.com/docs/functions/local-emulator
I got a Cload Firestore Database ready-to-go with some data in it.
I try to fetch data from Cload Firestore through my locally emulated cload functions.
My approach so far was following the "Writing the Cloud Function Code" section in https://cloud.google.com/community/tutorials/cloud-functions-firestore
My functions/src/index.ts file looks like this:
import * as functions from 'firebase-functions';
const Firestore = require('@google-cloud/firestore');
const cors = require('cors')({origin: true});
const admin = require('firebase-admin');
admin.initializeApp();
const PROJECTID = 'XYZ';
const firestore = new Firestore({
projectId: PROJECTID
});
const logger = function(object: any){
console.log(JSON.stringify(object));
}
export const create_order = functions.https.onRequest((request, response) => {
cors(request, response, () => {
// var test_doc_id = "82GKB2P6xee9lftOidDj";
const trucks = firestore.collection("trucks").get();
logger(trucks);
response.send(JSON.stringify(firestore));
});
});
I expected the value of "trucks" to be an array of all trucks coming from firestore, but there is no result "{}" coming back.
Can someone give me hints, guides and suggestions how to do this in a correct way ?
Best regards, and thanks for your help
Upvotes: 1
Views: 1788
Reputation: 426
I think you can control which DB functions are listening to with GOOGLE_APPLICATION_CREDENTIALS
environment variable. Running without will listen to local, while running with your production firebaseAdminSdkServiceAccount.json
will listen to changes on production DB.
On windows you would start it from terminal like this:
SET GOOGLE_APPLICATION_CREDENTIALS=/config/firebaseAdminSdkServiceAccount.json
firebase emulators:start
Then for listening for firestore document changes you reference:
const functions = require('firebase-functions');
functions.firestore.document('/mydoc/{mydocId}').onWrite(...)
EDIT: To make sure I'm right I did some googling, and came up with this explaination:
When using emulators:start we want to keep people inside the local emulation environment unless they specifically ask to be broken out. Right now, you can ask to contact production by manually restoring the GOOGLE_APPLICATION_CREDENTIAL files when running in the emulator.
https://github.com/firebase/firebase-tools/issues/1412#issuecomment-504561828
Upvotes: 1
Reputation: 1179
firestore.collection("trucks").get()
returns a Promise.
If you want to log out the data, you could write an asynchronous method:
cors(request, response, async () => {
const trucks = await firestore.collection('trucks').get();
logger(trucks);
// ...
});
Upvotes: 2