Raim Khalil
Raim Khalil

Reputation: 387

Firebase cloud function to loop through array and delete linked Data?

Currently, I have two children related in Firebase, conversations and posts.

  {
  "conversations" : {
    "-LFzccEzciNPSTFAZAhb" : {
      "49C91D37EE1C4B3E07FE24FEBE9ED72B" : "true",
      "CAD54A563CAB99107D9BBDB7F2234FA3" : "true",
      "Date" : "2018-06-27 05:06:12 +0000",
      "convoID" : "-LFzccEzciNPSTFAZAhb",
      "created_at" : 1.5300759725991712E9,
      "last_message" : "lesseee",
      "last_message_time" : 1530077715525,
      "postID" : "-LFzT4c6ylIcPne9F7QS",
      "status" : "sent",
      "timeOfDeletion" : 1530159609351
    },
    "-LFzd4rx4hCKtdls2yyF" : {
      "49C91D37EE1C4B3E07FE24FEBE9ED72B" : "true",
      "CAD54A563CAB99107D9BBDB7F2234FA3" : "true",
      "Date" : "2018-06-27 05:08:13 +0000",
      "convoID" : "-LFzd4rx4hCKtdls2yyF",
      "created_at" : 1.530076093932972E9,
      "last_message" : "feeling terrible",
      "last_message_time" : 1530077516414,
      "postID" : "-LFzd-uN4kRfU18TBj0N",
      "status" : "sent",
      "timeOfDeletion" : 1530162473644
    }
  },

and posts :

 "posts" : {
"-LFzT4c6ylIcPne9F7QS" : {
  "Revealed" : "false",
  "datePosted" : "2018-06-27 04:20:09 +0000",
  "post" : "Hey boys",
  "poster" : "49C91D37EE1C4B3E07FE24FEBE9ED72B",
  "revealedDate" : 1530073209351,
  "reveals" : 1,
  "revealsRequired" : 13,
  "timeOfDeletion" : 1530159609351,
  "watchedBy" : {
    "3ASP4M5mkTPGPO1qQhfVKXsr6Qf2" : "false",
    "AGdUYuWFJ9dC4VcPKeQJoMOM1xe2" : "false",
    "Hsm2R97Y1VZbhXHNrRvHuTKSrYv1" : "false",
    "Ih5m9VUnJnewKvqiZCVgBFwCFrz1" : "false",
    "N0IjBvmj9ieAKoBGpSJIitN6xmI3" : "false",
    "NMo1gUPKWFcdhsrnCbKte7JfrcA2" : "false",
    "NuAF78saM4OiaSlIVTtLD4gHWnp1" : "false",
    "OclP0yKT9ig6TtifF2ik1yh2TRr2" : "false",
    "XyF2qaRasbfNfwo6KM6ZClrsud42" : "false",
    "bc7gjBues0XWimaq3AKiLYRKJzc2" : "false",
    "dlwFYqlu2mgetB5zO6TNmFGBWcb2" : "false",
    "h42bS6QbVEdUkNJv2yjrU7L09HX2" : "-LFzccEzciNPSTFAZAhb",
    "i0U1oShLCWRVPezSzfUQl7VmwFB2" : "false",
    "kAfSAHHUWNcCKRjR28EtuXclWmE3" : "false",
    "mSWA8kF4XUMsK3fXDqx7iIBBJcb2" : "false",
    "qNWbYTlfYvXOIhNNjFkvrgjXCOk1" : "false",
    "yuUJHFcihgej6BFtCjXhL8cgLMC2" : "false"
  }
},

Every minute, a cron job is run on the database to delete old posts as such:

 exports.hourly_job =
  functions.pubsub.topic('hourly-tick').onPublish((event) => {
  const currentTime = Date.now()
  const getPostsForDate = admin.database().ref('posts').orderByChild('timeOfDeletion').endAt(currentTime); 

  return getPostsForDate.once('value', (snapshot) => {
        var updates = {};
        snapshot.forEach((childSnapshot) => {

            const postDetails = childSnapshot.val();
            const postIDtoDelete = childSnapshot.key

            updates[postIDtoDelete] = null

                })
            admin.database().ref('posts').update(updates)
        })
      });

In the database, if a user starts a conversation with a post, the watchedBy value in the post child will be changed from "false" to the ID of the conversation. Every minute, the cron job runs to delete the old post; however, the conversations need to be deleted, too. In an attempt to minimize data download usage, I associated the conversation ID with the watchedBy node. Now, when a child is deleted, how could I iterate through every user in the watchedBy child, see if the value is not "false", and if so, delete the conversation with that ID? I need to do this without downloading any more information, just accessing the data from the child snapshot. I am attempting to minimize data download usage too, so is this design feasible and efficient?

OLD CODE (before I tried minimizing data download usage)

exports.hourly_job =
  functions.pubsub.topic('hourly-tick').onPublish((event) => {
  const getPostsForDate = admin.database().ref('posts').on('value', (snapshot) => {
    const currentTime = Date.now()
        snapshot.forEach((childSnapshot) => {

            const postDetails = childSnapshot.val();

                const timeOfPostDeletion = postDetails.timeOfDeletion

                if (currentTime > timeOfPostDeletion) {

                     const postIDtoDelete = childSnapshot.key

                     const postDelete = admin.database().ref('/posts/'+ postIDtoDelete).remove()

                     const conversationsToRemove = admin.database().ref('/convoPosts/' + postIDtoDelete).on('value', (snapshot) => {
                            snapshot.forEach((childSnapshot) => {
                                const convoKey = childSnapshot.key
                                conversationReferenceDeletion = admin.database().ref('/conversations/' + convoKey).remove()
                            })
                     })



                }

        })

  })
    return true
  });

Edit : Attempt at iterating.

<!-- language: node.js -->


 const peopleWatching = postDetails.child('watchedBy').val()

            updates[postIDtoDelete] = null
            for (child in people) {
                let value = child.val();
                if (value !== "false") {
                    convoUpdates[value] = null
                }
            }

Upvotes: 0

Views: 2176

Answers (1)

Diego P
Diego P

Reputation: 1758

Please try this:

return admin.database().ref(`/watchedBy`).once('value').then(snap => {
  if (snap.hasChildren()) {
    const updates = {};
    snap.forEach(child => {
      if(child.val() !== "false"){
        updates[child.key] = null;
      }
    });
    return p.update(updates);
  }else{
    return null;
  }
});

Upvotes: 3

Related Questions