Advertisement
Guest User

Untitled

a guest
Jan 21st, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const functions = require('firebase-functions');
  2.  
  3. // The Firebase Admin SDK to access the Firebase Realtime Database.
  4. const admin = require('firebase-admin');
  5. admin.initializeApp();
  6. const db = admin.firestore()
  7.  
  8. // // Create and Deploy Your First Cloud Functions
  9. // // https://firebase.google.com/docs/functions/write-firebase-functions
  10. //
  11. // exports.helloWorld = functions.https.onRequest((request, response) => {
  12. //  response.send("Hello from Firebase!");
  13. // });
  14.  
  15. exports.addToFavorites = functions.firestore.document('users/{userId}/favorites/{favoriteId}')
  16.     .onCreate((snap, context) =>    
  17.     {
  18.         var favoritePost = snap.data();
  19.         //Get current count and increase by 1
  20.         var count = favoritePost.favoritesCount + 1;
  21.  
  22.         //Create new document in favoritesToUpdate
  23.         var addDoc = db.collection('favoritesToUpdate').add({
  24.           postId: favoritePost.docId,
  25.           userId: context.userId,
  26.           docId: context.favoriteId
  27.         }).then(ref => {
  28.           console.log('Added document to favoritesToUpdate with ID: ', ref.id);
  29.         }).catch( error => console.log(error));
  30.  
  31.         //Get all documents where postId = favoritePost.postId
  32.         var favoritesToUpdate = db.collection('favoritesToUpdate').where('postId', '==', favoritePost.postId);
  33.         var userRef = db.collection('users');
  34.  
  35.         return db.runTransaction((transaction) => {
  36.             return transaction.get(favoritesToUpdate).then((snapshot) => {
  37.                 for (let i = 0; i < snapshot.size; i++) { // Iterate through favoritesToUpdate
  38.                     var data = snapshot.docs[i].data();
  39.                    
  40.                     var userFavorites = userRef.doc(data.uid).collection('favorites').doc(data.docId);
  41.                     transaction.get(userFavorites).then((userFavorite) => {
  42.                         var updateObject = { favoritesCount: count };
  43.  
  44.                         transaction.update(userFavorite.ref, updateObject);
  45.                     });
  46.  
  47.                     //console.log(${data.uid}); // Get uid for each update of post
  48.                 }
  49.             });
  50.         }).catch( error => console.log(error));
  51.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement