Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get database value not related to the event in Cloud Functions for Firebase?

I have a firebase database and I am currently trying to use cloud functions to perform an operation when a value in my database changes. So far, it successfully triggers code to run when the value in my database changes. However, when the database value changes, I now need to check another value to determine it's status, and then perform an action after that. The problem is that I have ~0 experience with JS and I have no way of debugging my code other than deploying, changing the value in my database, and looking at the console log.

Is there any way to look up another value in the database and read it? How about look up a value and then set a value for it? Here is the code:

exports.determineCompletion =

functions.database.ref('/Jobs/{pushId}/client_job_complete')
    .onWrite(event => {

        const status = event.data.val();
        const other = functions.database.ref('/Jobs/' + event.params.pushId + '/other_job_complete');
        console.log('Status', status, other);

        if(status == true && **other.getValueSomehow** == true) {
            return **setAnotherValue**;
        }


    });

This code partially works, it successfully gets the value associated with client_job_complete and stores it in status. But how do I get the other value?

Additionally, if anyone has any JS or firebase documentation that they think would help me, please share! I have read a bunch on firebase here : https://firebase.google.com/docs/functions/database-events but it only talks about events and is very brief

Thank you for your help!

like image 694
Code Wiget Avatar asked Mar 30 '17 17:03

Code Wiget


People also ask

How do I check my Firebase database value?

You can use the GetValueAsync method to read a static snapshot of the contents at a given path once. The task result will contain a snapshot containing all data at that location, including child data. If there is no data, the snapshot returned is null . DataSnapshot snapshot = task.

What method is used to populate a Firebase reference with data?

Use the push() method to append data to a list in multiuser applications. The push() method generates a unique key every time a new child is added to the specified Firebase reference.

Is Firebase relational or non relational?

The key differences between Firebase and MySQL: Architecture: Firebase is a NoSQL database that stores and syncs data in real-time (a real-time document store); MySQL is an open-source relational database management system based on the domain-specific language SQL.


2 Answers

When writing a database trigger function, the event contains two properties that are references to the location of the data that changed:

event.data.ref
event.data.adminRef

ref is limited to the permissions of the user who triggered the function. adminRef has full access to the database.

Each of those Reference objects has a root property which gives you a reference to the root of your database. You can use that reference to build a path to a reference in another part of your database, and read it with the once() method.

You can also use the Firebase admin SDK.

There are lots of code samples that you should probably look at as well.

like image 193
Doug Stevenson Avatar answered Sep 30 '22 12:09

Doug Stevenson


I'm maybe a bit late, but I hope my solution can help some people:

exports.processJob = functions.database.ref('/Jobs/{pushId}/client_job_complete').onWrite(event => {

    const status = event.data.val();

    return admin.database().ref('Jobs/' + event.params.pushId + '/other_job_complete').once('value').then((snap) => {

        const other = snap.val();
        console.log('Status', status, other);

        /** do something with your data here, for example increase its value by 5 */
        other = (other + 5);

        /** when finished with processing your data, return the value to the {{ admin.database().ref(); }} request */
        return snap.ref.set(other).catch((error) => {
            return console.error(error);
        }); 
    });
});

But take notice of your firebase database rules.

If no user should have access to write Jobs/pushId/other_job_complete, except Your cloud function admin, You need to initialize Your cloud function admin with a recognizable, unique uid.

For example:

const functions         = require('firebase-functions');
const admin             = require('firebase-admin');
const adminCredentials  = require('path/to/admin/credentials.json');

admin.initializeApp({
    credential: admin.credential.cert(adminCredentials),
    databaseURL: "https://your-database-url-com",
    databaseAuthVariableOverride: {
        uid: 'super-special-unique-firebase-admin-uid'
    }
});

Then Your firebase database rule should look something like this:

"client_job_complete": {
    ".read": "auth !== null",
    ".write": "auth.uid === 'super-special-unique-firebase-admin-uid'"
}

Hope it helps!

like image 36
Unkn0wn0x Avatar answered Sep 30 '22 13:09

Unkn0wn0x