Monday, June 28, 2021

Firebase functions - tips and tricks

Functions emulator

Start emulator:

    firebase emulators:start

Stop emulator:

    sudo lsof -i tcp:<port> 

    kill -9 <process id>

    close the localhost webpage

    close the terminal window

Deploy to production

    firebase deploy --only functions

Debug

In the function body, we can log the performance:

    functions.logger.log("tag", "some text", original);

or:

    console.log("tag", "some text"); 

Then we can see logs in the Emulator supra:

It is so valuable, logs how certain code line in the functions file, e. g. on the screenshot above we see "index.js:49".

Also, logs are at the Firebase Console if functions are deployed to production:

Get data

Official Firebase manual provides sample code for trigger functions. In the function, we might need to get data of the certain document the function is called for.

exports.respondToRequest = functions.firestore
    .document('requests/{requestId}')
    .onUpdate((change, context) => {
              const requestUpdated = change.after.data();
              const requestPrevious = change.before.data();
              const respondedUpdated = requestUpdated.responded;
              const respondedPrevious = requestPrevious.responded;
              const topic = context.params.requestId;

          }
        );

I emphasize here two main parameters: "change" and "context". So "change" is to get values of the document fields. Context is to get id of the document only. E. g. if we log output of change and context:

              console.log("change data is:", change.after.data());
              console.log("context data is:", context.params);

We can get the full set of data available to be extracted:

        07:17:42
        function[us-central1-respondToRequest]
        change data is: { description: 'first request', responded: true }
        07:17:42
        function[us-central1-respondToRequest]
        context data is: { requestId: 'HBQ7cRYAT5yliHdWNnpc' }

No comments:

Post a Comment