How to use firebase cloud functions for logic on firestore data

Viewed 49

I am new to using firebase and have been trying to move some logic from the client to the server in the interest of keeping data more secure.

below is my working client side code that I have been trying to move onto using cloud functions.


const swipeRight = async (cardIndex) => {
        // card index is a reference to the card you swiped on
        // if the user doesn't exist in the database
        if (!profiles[cardIndex]) return;

        // userSwiped is the person that the user swiped right on
        const userSwiped = profiles[cardIndex];
        const userSwipedId = profiles[cardIndex].id;

        // adds the userSwipedId to the liked collection of the user
        setDoc(doc(db, "user", user.uid, "liked", userSwiped.id), userSwiped);

        // this is where we get the users ID
        const loggedInProfile = await (
            await getDoc(doc(db, "user", user.uid))
        ).data();

        // check if user (convert to firebase cloud function asap)
        // start of cloud function

        // get a document snapshot if the user ID is in the liked collection of the userSwiped
        let isMatch = getDoc(
            doc(db, "user", userSwiped.id, "liked", user.uid)
        ).then((documentSnapshot) => {
            if (documentSnapshot.exists()) {
                console.log("matched with", userSwiped.displayName);
                return true;
            } else return false;
        });
        // end of cloud function


        if (isMatch) {
            createMatchInDb(user, userSwiped, loggedInProfile);
            // navigate to match screen on match
            navigation.navigate("Match", {
                loggedInProfile,
                userSwiped,
            });
            let isMatch = false;
        }
    };

The above works well. It takes the list of liked users from the userSwiped and then checks if the userSwiping is in it. The cloud function will return true or false and an action will be performed on true

I have two ideas for possible solutions but I have not been able to get them to work yet.

the first

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.checkMatch = functions.firestore
    .document("/user/{userSwiped}/liked")
    .onUpdate((snap, context) => {
      {
        // check here whether the userSwiping is present in the userSwiped list of liked users.




      }
    });

the second

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

exports.checkMatch = functions.firestore
    .onCall((data, context) => {
      {
        // how do I query the database to check if the user swiping 
        // is present in the userSwiped array of liked users?
      }
    });

below is a screenshot of my firestore. screenshot of the firestore database

I have spent many hours reading through the documentation but am completely stumped by how to actually query the data from the database to use in my logic. Returning the outcome does not seem like an issue but I am struggling to make the connection and actually get data from the database via cloud functions.

Any help or advice would be greatly appreaciated, I have spent a large amount of time already looking for blogs or other explanations but have come up a little short on a working test.

thanks

1 Answers
exports.checkMatch = functions.https.onCall((data, context) => {
  const userId = context.auth.uid;
  return new Promise((resolve, reject) => {
    const db = admin.firestore();
    db.collection(`/user/${userId}/liked`)
        .get()
        .then((snapshot) => {
          if (!snapshot.empty) {
            resolve({"result": true});
          } else {
            resolve({"results": false});
          }
        })
        .catch((reason) => {
          console.log(
              `reason:  + ${reason}`
          );
          reject(reason);
        });
  });
});

I'm not sure how but I managed to luck my way into this working solution. I hope this helps someone who has the same issue one day.

Related