简体   繁体   中英

Use live/online firestore in local Functions firebase emulator

I am making a cloud function and using the firebase local emulator. Node.js

I follow this guide where it uses the firestore on the local machine. But i want to use my firestore that already is online. Is there any way to achieve this?

I understand that you want to test your function within local emulator, but use cloud database.

This is possible, although I don't think it very helpful. You can test easier deploying your function to the cloud. Anyway....

When you test both in emulator and you have both on cloud it's enough to initiate like this (its from here ):

const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

However if you want to connect from local to cloud you need to initialize like "Initialize on your own server" from the same doc.

I have created similar example from helloworld function working on my side (showing all fields of the docs). I have collection "users" and document "1" in my firestore:

const functions = require("firebase-functions");
const admin = require('firebase-admin');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {   
  
       const serviceAccount = require('./serviceAccountKey.json');
       admin.initializeApp({
               credential: admin.credential.cert(serviceAccount)
       });
       const db = admin.firestore();
       const ref = db.collection('users').doc('1');
       ref.get().then((doc)=> {
               functions.logger.info(doc, {structuredData: true});
               response.send('Document data:'+JSON.stringify(doc.data()))
       }).catch(e => {
               console.log('error; '+e)
       })
});

The serviceAccountKey.json you can easily generate in Firebase console in Project settins/Service Accounts tab. Just remember that if you want to deploy to cloud you should change the app initialization.

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