[英]Use live/online firestore in local Functions firebase emulator
I am making a cloud function and using the firebase local emulator.我正在制作云 function 并使用 firebase 本地仿真器。 Node.js Node.js
I follow this guide where it uses the firestore on the local machine.我按照本指南使用本地计算机上的 firestore。 But i want to use my firestore that already is online.但我想使用我已经在线的 Firestore。 Is there any way to achieve this?有什么办法可以做到这一点?
I understand that you want to test your function within local emulator, but use cloud database.我了解您想在本地模拟器中测试您的 function,但使用云数据库。
This is possible, although I don't think it very helpful.这是可能的,虽然我不认为它很有帮助。 You can test easier deploying your function to the cloud.您可以测试更轻松地将 function 部署到云。 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).我从 helloworld function 中创建了类似的示例(显示文档的所有字段)。 I have collection "users" and document "1" in my firestore:我的firestore中有集合“用户”和文档“1”:
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.您可以在 Firebase 控制台的项目设置/服务帐户选项卡中轻松生成serviceAccountKey.json
。 Just remember that if you want to deploy to cloud you should change the app initialization.请记住,如果您想部署到云,您应该更改应用程序初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.