I am learning firebase, and I created the following example. I created a Cloud Function by uncommenting out the example and I pushed it to live:
const functions = require("firebase-functions");
// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions
exports.helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello logs!", {structuredData: true});
response.send("Hello from Firebase!");
});
This code was pushed to live and then confirmed by the firebase gui. My issue is, when I invited another email to the project, ran firebase init from this email, and went through the brief setup instructions, the code was still commented out in the new local project. What am I doing wrong here? Is there some kind of firebase pull command where I can get the exact code from my project to local?
Running firebase init does not get the existing code for a project. If you want to share the code with a collaborator, you'll have to use another tool for that, such as github or gitlab.
Related
I want to test my firebase back-end involving firestore, auth, and functions. There are cloud functions on new user created or deleted and rest like apis all affecting firestore data.
I want to run test like this.
I will start firebase emulator (with no data) in a terminal.
Run test file. Following everything will be in a script, so no part is manual.
I will register new users. Those should trigger firebase functions lets say affecting users collection.
Test if the users collection is affected.
Then do a fake login with any created user say Jake Williams.
Call some rest api. Those api will again change firestore data. For these cloud functions auth received will be of Jake Williams
Test if those firestore data is affected.
Clean emulator data and run other tests.
I have gone through docs, yet these is unclear. Went through github/quickStart-testing, still no help. I see there are tutorial which test firestore rules and some test cloud functions separately.
Can I setup a test project to work like my above requirements?
I find Firebase guide confusing. There they mentioned firebase emulators:exec "./my-test.sh", not sure my-test.sh is. Normally not seen .sh file in node.js testing workflow. After 2-3 days, found the proper solution to my own question.
Here are some things you should know.
firebase emulators:exec
firebase emulators:exec 'npm run test' command run your test files within firebase emulator. So when your test files are using firebase admin import * as admin from "firebase-admin"; I think this firebase admin will be linked to that emulator instance being created. Running admin.auth().createUser(...) in that test file, then user will be created on that emulator. This createUser will also trigger side effects in cloud functions. You just have to wait for 5 sec before testing triggered functions effects.
You need to init admin and firebase function test with your project id
import functionTest from 'firebase-functions-test'
import * as admin from "firebase-admin";
const PROJECT_ID = "your project id"
const test = functionTest({
projectId: PROJECT_ID,
});
admin.initializeApp({
projectId: PROJECT_ID,
})
If you want to clear emulator data and reinit app between each tests
import axios from 'axios'
import * as admin from "firebase-admin";
const PROJECT_ID = "your project id"
const deletingFirebaseDataUrl: string = `http://127.0.0.1:8080/emulator/v1/projects/${PROJECT_ID}/databases/(default)/documents`;
const deletingAuthDataUrl: string = `http://localhost:9099/emulator/v1/projects/${PROJECT_ID}/accounts`;
async function initApps() {
admin.initializeApp({
projectId: PROJECT_ID,
})
}
async function deleteAllDataAndApps() {
admin.apps.forEach(app => app?.delete());
await axios.delete(deletingFirebaseDataUrl) //
await axios.delete(deletingAuthDataUrl)
test.cleanup();
}
beforeEach(initApps)
afterEach(deleteAllDataAndApps)
Going through the docs, I did not find these things or they were not clear to me.
Hi I am running firebase node project locally with Firestore, Functions and Auth emulators. When I try signing in with popup I get an empty popup with no dummy login. Please find image and code below. I don't understand with there is no dummy data. Works perfectly fine when connecting to production environment. Please can anyone explain why I don't see any accounts?
// Get a Firestore instance
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const functions = getFunctions(app);
export const db = getFirestore(app);
if (process.env.NODE_ENV === "development") {
connectAuthEmulator(auth, "http://localhost:9099/");
connectFunctionsEmulator(functions, "localhost", 5001);
}
Clicking on add new account does nothing.
Node service
you might be doing something wrong here
would recommend going through this article and hope you find a work around.
https://firebase.google.com/docs/emulator-suite/connect_auth
Your question is ambiguous. What accounts are you expecting to see in that popin? If you want to see the accounts you created using the SDK (client or admin), you need to go to the emulator UI, available by default on localhost:4000 and then check the Auth tab.
The popin in your screenie is only there to generate federated accounts.
I tried to do my first project on Google Cloud Functions.
I tried the code provided by google :
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
// Take the text parameter passed to this HTTP endpoint and insert it into
// Cloud Firestore under the path /messages/:documentId/original
exports.addMessage = functions.https.onRequest(async (req, res) => {
// Grab the text parameter.
const original = req.query.text;
// Push the new message into Cloud Firestore using the Firebase Admin SDK.
const writeResult = await admin
.firestore()
.collection("messages")
.add({ original: original });
// Send back a message that we've succesfully written the message
res.json({ result: `Message with ID: ${writeResult.id} added.` });
});
Everything is working fine as expect.
But, I have to visit the url returned by the command:
$ firebase deploy --only functions
It returns me a url that i must visit to run the function.
My question is: for Database Triggers, do I have to open the url through the browser to execute the functions?
For Database Triggers, do I have to open the url through the browser
to execute the functions?
No, for database triggers (Firestore or the Realtime Database), which are background triggers, you don't need to call an URL: the Cloud Function is triggered accordingly to the handler used to define the Function (e.g. onCreate(), onUpdate(), etc. for Firestore or onWrite(), onCreate(), etc. for the Realtime Database).
There is actually no URL available for background triggered Cloud Functions.
I am trying to write a cloud function which gets executed every time a sensor reading in the collection "sensor-readings" gets created:
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.createNotification = functions.firestore
.document('sensor-readings/{sensorId}')
.onCreate((snap, context) => {
const payload = {
notification: {
title: 'New news',
body: "Body Test"
}
};
// perform desired operations ...
return admin.messaging().sendToTopic("topic",payload);
});
The cloud function gets executed everytime a sensor reading is created but when I try to use
gcloud pubsub subscriptions pull --auto-ack MySub
to test the outcome of the function, there is no message being published to the topic.
Any ideas?
Thanks
This code is working with a product called Firebase Cloud Messaging, which is meant for sending message to web and mobile applications:
admin.messaging().sendToTopic("topic",payload);
But your command line is working with Google Cloud Pubsub, which is a completely different product:
gcloud pubsub subscriptions pull --auto-ack MySub
You can't use FCM to send messages to a pubsub topic. Again, they are completely different. And you can't use gcloud to see what's happening with FCM messages. You would need to do that in your web or mobile app.
If you want to send a messages to a pubsub topic, you should use the Google Cloud SDK for that, not the Firebase Admin SDK.
Screenshot attached when I entered "Firebase deploy" command
I was trying to execute this set on instructions while deploying webhook using Google Cloud Functions for Firebase and the static resources needed by the project using Firebase Hosting:
Run firebase init, and select to configure Hosting and Functions. Select the project. In the configuration wizard, accept all the default choices.
Generate a private key using Firebase Settings/Service Accounts, and edit functions/database.js with the path to the JSON cert file. Now populate the database: node database.js
Run firebase deploy and take note of the endpoint where the fulfillment webhook has been published. It should look like Function URL (yourGame): https://us-central1-YOUR_PROJECT.cloudfunctions.net/yourGame. The command will also deploy the static assets at https://us-central1-YOUR_PROJECT.cloudfunctions.net/.
On running firebase deploy I can't find the "Function URL". It would just display "Hosting URL" and "Project Console".
A screenshot is attached upon running "firebase deploy" on CLI.
And also what does it mean by "Now populate the database: node database.js"?
Follow this Project Console URL.
You then should be in your project's dashboard, on the left side of the screen you gonna see a bunch of options, among them one called "Functions", click on it.
Your URL should be displayed there.
If you created a new Firebase project, then your index.js in your ./functions directory will look like this by default:
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
//exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello World!");
//});
Make sure you uncomment the hellowWorld function. Then save your project. Then run firebase deploy. Then, the url will show up in your dashboard.