firebase serve and debugging functions? - javascript

I ran
firebase serve --only-functions
Then ran
functions inspect addMessage
So I could debug the addMessage function. Debugging however did not work.
Running
firebase deploy addMessage --trigger-http
firebase inspect addMessage
Did work and allow me to debug but it doesn't seem to support hot reloading.
Is it possible to have hot reloading and debugging working at the same time?
My index.js:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = "123";//req.query.text;
// Push the new message into the Realtime Database using the Firebase Admin SDK.
return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
// Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
return res.redirect(303, snapshot.ref.toString());
});
});

try: ndb firebase serve
debugger breakpoints are hit with stack traces visible, note it's a little slow so give the debugger time to instrument the child processes
Additionally I was able to debug cloud functions in isolation using (caps for removed values):
GCLOUD_PROJECT=THE-FIREBASE-PROJECT node --inspect-brk /path/to/functions-framework --target FUNCTION-NAME --port=5000
where functions-framework simply expands to the full path for the installed functions-framework (global in my case) from the working directory where the index.js file is for the target functions.
Alternately when or where the FIREBASE_CONFIG is needed try this format adjusted to fit:
FIREBASE_CONFIG="{\"databaseURL\":\"https://YOUR-FIREBASE-PROJECT.firebaseio.com\",\"storageBucket\":\"YOUR-FIREBASE-PROJECT.appspot.com\",\"projectId\":\"YOUR-FIREBASE-PROJECT\"}
https://github.com/GoogleChromeLabs/ndb
https://cloud.google.com/functions/docs/functions-framework
https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/15

As of firebase-tools v7.11.0, the Firebase emulator now supports attaching a debugger with the --inspect-functions option. This answer shows WebStorm-specific instructions that can be easily adapted to other debuggers.

Related

Can Firebase Emulators be used for integration testing with a React frontend?

I have a simple React frontend application that uses Firebase for Auth and Firestore (https://jlowen-netflix.netlify.app/ if additional context helpful). I provide Firebase as a Context to my top-level application, and listen for a change in Auth to redirect the user to logged in content.
I would like to test end-to-end user workflow from anonymous, to sign-up, to logged in. I have already installed the Firebase CLI as well as the Firebase emulators. I can verify the emulators run correctly by visiting the Emulator UI on localhost. I also can verify the application hooks in to the emulators when I start the dev server (npm start) for Create-React-App. I made a test user in the Emulator UI, and was able to log in as expected.
When I try to get this to render in Jest, my auth listener custom hook attempts to access the auth() method on the firebase context prior to firebase initialization.
TypeError: Cannot read property 'auth' of undefined
9 | // As recommended by Firebase - need to set up subscription
10 | useEffect(() => {
> 11 | const listener = firebase.auth().onAuthStateChanged((authUser) => {
| ^
12 | console.log(`Firebase detected auth change: ${authUser}`)
13 | if (authUser) {
14 | localStorage.setItem("authUser", JSON.stringify(authUser))
at src/hooks/use-auth-listener.js:11:31
I can't seem to resolve what seems to be some sort of async issue that I encounter in Jest, but does not occur in the deployed application.
I am pretty new in React and Jest, so if I can provide additional information, please let me know!
Unfortunately your error doesn't seem to be related to your main question. What the error you're showing says is that you forgot to import or require the firebase from somewhere. Read the firebase package docs and add something like this at the top of your file:
var firebase = require('firebase');
I would also be interested in connecting firebase app to local emulators, so will edit this answer if I figure something out. In the mean time.. sorry for the false hope.

Can I locally emulate cloud function and hosting at the same time?

I am writing a simple web app with firebase hosting and cloud functions. My functions are onCreate , onDelete and httpsServer. I wan't to test my app by running it locally. How can I do this since firebase serve only works with https function and hosting.
I have tried running firebase serve and firebase functions:shell at the same time on different bash terminals. This causes firebase functions:shell to fail.
The create function :
exports.created = functions.firestore.document('Books/{bookID}')
.onCreate((snapshot, context) => {
FUNCTION_BODY
});
The Delete Function :
exports.deleted = functions.firestore.document('Books/{bookID}')
.onDelete((snapshot, context) => {
FUNCTION_BODY
});
The https Function :
exports.app = functions.https.onRequest(app);
The error thrown from bash :
$ firebase functions:shell
i functions: Preparing to emulate functions.
Warning: You're using Node.js v10.13.0 but Google Cloud Functions only supports v6.11.5.
! functions: Failed to emulate created
! functions: Failed to emulate deleted
! functions: Failed to emulate app
i functions: No functions to emulate.
No functions emulated.
Output from second bash :
i functions: Preparing to emulate functions.
Warning: You're using Node.js v10.13.0 but Google Cloud Functions only supports v6.11.5.
i hosting: Serving hosting files from: public
+ hosting: Local server: http://localhost:5000
info: initalised
info: rendering home...
+ functions: app: http://localhost:5001/book-shelf-be347/us-central1/app
info: Worker for app closed due to file changes.
Note: These are separate bash terminals running at the same time on the same machine.
I did some digging through the firebase documentation and could not find any solution. This is probably because there is no official tools that let you do this. So I finally solved the problem by running the hosting using nodemon and then using
firebase serve --functions
This solved the problem of using same port since it is handled by nodemon.
Hope firebase will provide new tools in the future.

Firebase function log not displaying data

Here is a screenshot of my firebase console, notice how it is empty
I have recently added Firebase to my project and have made sure that the firebase modules I want are already installed in my functions folder. I have the following code in my index.js file:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// // 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 from Fire!");
console.log('I am a log entry!')
});
I have followed the Firebase Cloud Functions tutorial video step for step and from my understanding the string I am a log entry! should be displaying in my firebase console under the logs tab along with the name of the deployed function. However it remains empty and neither the function or the log data shows. I was wondering why this was. Is my code incorrect? All help is appreciated, thanks in advance.
You need to execute following commands in your functions directory to make sure it has been deployed:
firebase login
firebase init functions
npm install
and then:
firebase deploy --only functions
If deployment failed, you should see this wiyhin the logs provided by last command

Can't deploy Cloud Functions for Firebase

I was deploying functions just fine, but then it stopped working, and I don't know why. I've reverted back to the sample code (from here or here):
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
});
But now, when I run firebase deploy --only functions I get:
=== Deploying to 'mydb'...
i deploying functions
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...
+ runtimeconfig: all necessary APIs are enabled
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (2.04 KB) for uploading
! functions: Upload Error: Cannot read property 'response' of undefined
i starting release process (may take several minutes)...
i functions: updating function makeUppercase...
! functions[makeUppercase]: Deploy Error: Function load error: Node.js module defined by file index.js is expected to export function named makeUppercase
+ functions: 0 function(s) deployed successfully.
Functions deploy had errors. To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
What is wrong?
The console shows the same error messages, without any more explanations:
Version 3.6.0 of the Firebase Tools just came out... after installing that version, the deploy worked fine!
Inside your project by the terminal:
npm install
firebase deploy
It's much helpful to examine the actual logs by viewing the log
firebase functions:log
The specific issue will be visible there. I sometimes had error as simple as a missing package

Cloud Functions for Firebase Error occurred while parsing your function triggers

I had been trying to send emails to the users in Firebase using Cloud Functions for Firebase. I am referring to the repository of firebase function at https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users
I install all the node packages for the firebase email function as required and explained on the repository.
I edited TODO in the index.js file in functions as
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
firebase functions:config:set gmail.email="email#gmail.com" gmail.password="gmailPassword"
const gmailEmail = encodeURIComponent(functions.config().gmail.email);
const gmailPassword = encodeURIComponent(functions.config().gmail.password);
const mailTransport = nodemailer.createTransport(
`smtps://${gmailEmail}:${gmailPassword}#smtp.gmail.com`);
When I try to deploy the function using the command
firebase deploy
It shows me the following error
Error occurred while parsing your function triggers.
Could anyone please help me out in solving this.
The functions:config is a command that you run with the Firebase CLI from the command prompt, not from your Functions code.
So in your command prompt/terminal:
firebase functions:config:set gmail.email="email#gmail.com" gmail.password="gmailPassword"

Categories

Resources