Emilis
Emilis

Reputation: 162

Firebase check if node exist return true or false

I have this firebase realtime database: Firebase tree

I am making dating app, similar to tinder for my bachelor. I am creating match system now.

I created onCreate listener to check when the user presses like button and to check if another user already pressed like on current user. So this is what i tried.

exports.UserPressesLike = functions.database
  .ref('/users/{userId}/matches/{otherUserId}')
  .onCreate((snapshot, context) => {
    // Grab the current value of what was written to the Realtime Database.
    const original = snapshot.val();
    const userId = context.params.userId;
    const matchedUserId = context.params.otherUserId;
    const a = checkUserMatch(userId, matchedUserId);
    if (a === true) {
      console.log('Its a match');
    } else {
      console.log('There is no match');
      console.log(a);
    }

    return null;
  });

checkUserMatch = async (userId, matchedUserId) => {
  const snapshot = await admin
    .database()
    .ref('/users/' + matchedUserId + '/matches/' + userId)
    .once('value')
    .then(snapshot => {
      // let tempuserId = snapshot.val();
      // if()
      return true;
    });
};

I want checkUserMatch to return true if there is that node, and false if there is no such node.

Upvotes: 0

Views: 761

Answers (2)

Stratubas
Stratubas

Reputation: 3067

After doing Puf's fix, you can check if snapshot.val() !== null, or use the shortcut snapshot.exists().

And you better rename your const snapshot to const isLiked, and then actually return that isLiked (or that function will return undefined).

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 599071

Your checkUserMatch is asynchronous (as shown by the fact you marked it with async), which means that it doesn't immediately return a value, but return an object that will eventually contain a value (a so-called promise).

To call an async function, you need to call it with await:

const a = await checkUserMatch(userId, matchedUserId);

This means that you also need to mark the function containing the call as async, so:

exports.UserPressesLike = functions.database
  .ref('/users/{userId}/matches/{otherUserId}')
  .onCreate(async (snapshot, context) => {

Note that I highly recommend not continuing before you've learned more about asynchronous APIs, Promises and async / await. For example, by watching Doug's video series Learn JavaScript Promises with HTTP Triggers in Cloud Functions.

Upvotes: 2

Related Questions