Currently I'm building a nodejs express REST api using the below to access Firestore from my Google Cloud Platform:
const Firestore = require("#google-cloud/firestore");
const db = new Firestore();
const docRef = db.collection('users').doc('alovelace');
const ada = await docRef.set({
first: 'Ada1',
last: 'Lovelace',
born: 1815
});
It picks up the keys from GOOGLE_APPLICATION_CREDENTIALS in a .env file.
Of course I want to develop locally rather than remotely constantly and I've come across the Firebase Firestore Emulator.
I've attempted to use db.useEmulator() but that isn't part of google cloud/firestore but is part of firebase-admin.
Is there any way of using the firestore emulator without going down the firebase-admin route?
The Node.js SDK for client-side development also has a useEmulator call, so you should be able to connect it to the Firestore emulator in the same way.
Related
Hi i am having firebase cloud functions, When i run firebase emulator in local they are not displaying in emulator.below is my functions code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const DomParser = require('dom-parser')
admin.initializeApp(functions.config().firebase);
exports.storeBooking = functions
.region("europe-west1")
.pubsub.topic("responses")
.onPublish((message) => {
/// some logic
});
when i run emulator must show function storeBooking, But in emulator it is showing as below
Watching "D:\backend-functions\booking" for Cloud Functions...
function ignored because the pubsub emulator does not exist or is not running.
function ignored because the pubsub emulator does not exist or is not running.
The emulator will show like this:
Watching "D:\backend-functions\booking" for Cloud Functions…
function ignored because the pubsub emulator does not exist or is not running.
function ignored because the pubsub emulator does not exist or is not running.
Which means function was found but for some reason firebase cannot connect to pubsub emulator, despite all the configs.
As per the documentation, you need to set up admin credentials to test your functions to interact with Google APIs or other Firebase APIs via the Firebase Admin SDK.
The cloud pubsub requires the setup steps described in this section. This applies whether you're using the Cloud Functions shell or firebase emulators:start.
You can follow the instructions To set up admin credentials for emulated functions from documentation.
For more information you can check with this Stackoverflow Link.
I would like to test the Google Cloud Speech-to-Text API from within Firebase Emulators. I currently have a trigger set on Firebase Storage that automatically gets fired when I upload a file via the Emulator Storage UI. This makes a request to the Speech to Text API, but I keep getting a permission denied error, as follows:
Error: 7 PERMISSION_DENIED: Cloud Speech-to-Text API has not been used in project 563584335869 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/speech.googleapis.com/overview?project=563584335869 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.
I understand that project 563584335869 is the Firebase Cli project.
I have set the following environment variables when starting the emulator:
export GCLOUD_PROJECT=my-actual-glcloud-project-id && export FIREBASE_AUTH_EMULATOR_HOST='localhost:9099' && export GOOGLE_APPLICATION_CREDENTIALS=./path/to/service-account.json &&
firebase emulators:start
The service_account.json key file is associated with a service_account that has the following roles, as demonstrated by running
gcloud projects get-iam-policy my_project_id --flatten="bindings[].members" --format='table(bindings.role)' --filter="bindings.members:serviceAccount:my_service_account#my_project_id.iam.gserviceaccount.com"
ROLE
roles/speech.admin
roles/storage.admin
roles/storage.objectAdmin
roles/storage.objectCreator
roles/storage.objectViewer
Since the credentials for the service account I am using should have admin access to the speech to text api, why do I keep getting a permission denied error when running from the emulator, and how can I fix it?
The project id 563584335869 is not yours. It is firebase-cli cloud project’s project-id. In this case, the problem is arising because you have to set your own configuration using your credentials or your key.
You can see below a code for NodeJS which I found in github[1] where it shows how to configure your authentication to use the API.
// Imports the Google Cloud client library
const textToSpeech = require('#google-cloud/text-to-speech');
// Create the auth config
const config = {
projectId: 'grape-spaceship-123',
keyFilename: '/path/to/keyfile.json'
};
// Creates a client
const client = new textToSpeech.TextToSpeechClient(config);
[1]https://github.com/googleapis/nodejs-text-to-speech/issues/26
EDIT
There are different ways to set up your authentication for speech to text. One way to resolve this problem would be to add the same auth configuration as the Text-to-Speech and it should look something like this in your code.
// Imports the Google Cloud client library
const speech = require('#google-cloud/speech');
// Create the auth config
const authconfig = {
projectId: 'grape-spaceship-123',
keyFilename: '/path/to/keyfile.json'
};
// Creates a client
const client = new speech.SpeechClient(authconfig);
Another way to solve this problem according to this Google Cloud Documentation[2] is to setup your authentication.
[2]https://cloud.google.com/speech-to-text/docs/libraries#setting_up_authentication
Due to problems using a Realtime Database emulator for development in Flutter (see How do I connect to my local Realtime Database emulator in my Flutter app?), I am now simply using my non-local Realtime Database for development. However, I am also using Cloud Functions, and I have created a Functions emulator.
I tried the following to connect to it, based on this StackOverflow-answer:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
functions.config = () => {
return {
firebase: {
databaseURL: "https://mylink.firebaseio.com/",
},
};
};
But the emulator is not responding to changes in the database.
So, is it even possible to connect my local Functions emulator to my non-local Realtime Database? It's kind of a weird setup, but I don't know how I am going to be able test functions otherwise.
It's not possible to have the local Cloud Functions emulator respond to (or "trigger" on) events in a production database. You have to deploy your functions in order for them to execute in response to change in the cloud-hosted database. The local functions emulator only responds to changes in the locally emulated database.
I'm learning GCP and in their Firestore, I'm confused with the difference of Admin.firestore & Firebase.firestore.
this is the code for admin:
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://<firestoreprojectnameurl>"
const db = admin.firestore();
});
while this is the code for the firestore
const { config } = require('./config');
const firebase = require("firebase");
firebase.initializeApp(config);
const db = firebase.firestore();
Please note that only 1 db at a time will work and for my current set-up I use the db = firebase.firestore() although if I change it to db = admin.firestore ite works fine and all my code works the same.
Thank you in advance!
The JavaScript SDK for web clients (your second example) is different than the JavaScript SDK for nodejs backends (your first example). They have different APIs, though they might appear very similar for most types of queries. But they are definitely not interchangeable. You are supposed to pick the one that matches the environment where it's going to be used. The Firebase Admin SDK is definitely not usable in web clients, though the web client SDK might work in nodejs backend environments (but I don't recommend it).
It might also help to know that the Firebase Admin SDK is actually just a wrapper around the Google Cloud nodejs SDK. You can compare the API documentation of the web SDK to the nodejs SDK if you want to take a closer look.
I am trying to write a function that writes to a different database when a user writes to the default database ,
I did my research and i am a little bit confused
I saw this on firebase
var admin = require('firebase-admin');
var serviceAccount =
require('path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL:
'https://<DATABASE_NAME>.firebaseio.com'
});
And also this
const app1 = firebase.initializeApp({
databaseURL: "https://testapp-1234-1.firebaseio.com"
});
const app2 = firebase.initializeApp({
databaseURL: "https://testapp-1234-2.firebaseio.com"
}, 'app2');
// Get the default database instance for an app1
var database1 = firebase.database();
// Get a database instance for app2
var database1 = firebase.database(app2);
So my question is do we need the service.json file which holds the secret key when using cloud functions admin SDK
For almost all typical use cases, you don't need to provide a service account when working with the Firebase Admin SDK in Cloud Functions. This is because Cloud Functions provides the credentials for the default service account in the project where the function is deployed. (This account can be seen as the App Engine default service account in the Cloud console.)
It's strongly recommended to initialize the Admin SDK with no arguments and accept this default account:
const admin = require('firebase-admin');
admin.initializeApp(); // accept the default service account
As part of taking this default, the Admin SDK will also understand the URL of your default Realtime Database shard, and the URL of your default Cloud Storage bucket. You won't need to provide these values. As such, your code will be much more easy to port to other projects.
If you need to access non-default resources of your project, you can also initialize other instances of firebase-admin to point to those that you explicitly configure. This is what your second code sample is illustrating. If you don't have any non-default resources to access, then don't bother with this.
If there is something that the service account can do, you can grant that role in the Cloud console. The one notable action that this account currently can't perform by default is cryptographic signing of blobs. In practical terms, this means it can't generate signed URLs for object stored in Cloud Storage. This is a fairly common thing to do in Cloud Functions. To remedy this, you need to grant the signBlob role to the default service account.