Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const functions = require('firebase-functions');
- // The Firebase Admin SDK to access the Firebase Realtime Database.
- const admin = require('firebase-admin');
- admin.initializeApp();
- const db = admin.firestore()
- // // 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 Firebase!");
- // });
- exports.addToFavorites = functions.firestore.document('users/{userId}/favorites/{favoriteId}')
- .onCreate((snap, context) =>
- {
- var favoritePost = snap.data();
- //Get current count and increase by 1
- var count = favoritePost.favoritesCount + 1;
- //Create new document in favoritesToUpdate
- var addDoc = db.collection('favoritesToUpdate').add({
- postId: favoritePost.docId,
- userId: context.userId,
- docId: context.favoriteId
- }).then(ref => {
- console.log('Added document to favoritesToUpdate with ID: ', ref.id);
- }).catch( error => console.log(error));
- //Get all documents where postId = favoritePost.postId
- var favoritesToUpdate = db.collection('favoritesToUpdate').where('postId', '==', favoritePost.postId);
- var userRef = db.collection('users');
- return db.runTransaction((transaction) => {
- return transaction.get(favoritesToUpdate).then((snapshot) => {
- for (let i = 0; i < snapshot.size; i++) { // Iterate through favoritesToUpdate
- var data = snapshot.docs[i].data();
- var userFavorites = userRef.doc(data.uid).collection('favorites').doc(data.docId);
- transaction.get(userFavorites).then((userFavorite) => {
- var updateObject = { favoritesCount: count };
- transaction.update(userFavorite.ref, updateObject);
- });
- //console.log(${data.uid}); // Get uid for each update of post
- }
- });
- }).catch( error => console.log(error));
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement