Kento Nishi
Kento Nishi

Reputation: 598

Firebase Functions - Writing to Database

I'm extremely new to Firebase Functions and node.js, and I need help writing a function that completes the following workflow.

1: Listen to a write event at "/dir1/{PUSH-ID}/dir2/{MESSAGE-ID}".

2: Read data from a directory at "/dir1/{PUSH-ID}/dir2/dir3".

2.5: For each item in "/dir1/{PUSH-ID}/dir2/dir3", get the key.

3: For each key, "clone" the data from the original write to "/dir4/{key}/dir5/{MESSAGE-ID}".

How can I do this? Thanks in advance!

Upvotes: 1

Views: 367

Answers (1)

James Poag
James Poag

Reputation: 2380

// 1: Listen to a write event at "/dir1/{PUSH-ID}/dir2/{MESSAGE-ID}".
exports.propagateMessages =
  functions.database.ref('/dir1/{PUSH_ID}/dir2/{MESSAGE_ID}')
    .onWrite((change, context) => {
      // Do Nothing when the data is deleted...
      if (!change.after.exists()) {
        // Perhaps you intend to delete from cloned dirs?
        // if so, left as reader's exercise, just follow from below
        return null;
      }
      else {
        let pushId = context.params.PUSH_ID;
        let messageID = context.params.MESSAGE_ID;

        let fireDB = change.after.ref.root;

        // 2: Read data from a directory at "/dir1/{PUSH-ID}/dir2/dir3".
        return fireDB.child(`/dir1/${pushId}/dir2/dir3`).once('value')
          .then(listenersSnapshot => {

            let listener_promises = []; // collection of writes

            // 2.5: For each item in "/dir1/{PUSH-ID}/dir2/dir3", get the key.
            listenersSnapshot.forEach(childSnapshot => {
              let child_key = childSnapshot.key;

              // 3: For each key, "clone" the data from the original write to "/dir4/{key}/dir5/{MESSAGE-ID}".
              listener_promises.push(
                fireDB.child(`/dir4/${child_key}/dir5/${messageID}`).set(change.after.val())
              );
            });

            // wait on all writes to complete
            return Promise.all(listener_promises);
          })
          .catch(err => {
            console.log(err);
          });
      }
    })

Upvotes: 3

Related Questions