title: push notifications to a group using Firebase functions
body: <p>I'm working on an app that uses firebase for messaging. I want to use functions to send out push notifications when there is a new message in a group. Unfortunately, I have zero experience with node.js as I don't have a CS background and only a few months of coding experience.</p>
  
  <p>I've tried to piece it together from tutorials I could find, but I'm not even sure if I'm headed in the right direction.</p>
  
  <p>This is for an iOS App if that makes any difference</p>
  
  <p>Here's my firebase structure</p>
  
  <p><a href="https://i.stack.imgur.com/cURTQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cURTQ.png" alt="enter image description here"></a></p>
  
  <p>Here's what I have so far </p>
  
  <pre><code>let functions = require('firebase-functions');
  let admin = require('firebase-admin');
  admin.initializeApp(functions.config().firebase);
  exports.sendPush = functions.database.onWrite(event =&gt; {
  let projectStateChanged = false;
  let projectCreated = false;
  let projectData = event.data.val();
  
  if (!event.data.previous.exists()) {
      projectCreated = true;
  }
  if (!projectCreated &amp;&amp; event.data.changed()) {
      projectStateChanged = true;
  }
  var valueObject = event.data.val();
  
  return loadUsers().then(users =&gt; {
      let tokens = [];
      for (let user of users) {
          tokens.push(user.pushToken);
      }
      let payload = {
          notification: {
              title: valueObject.RealName,
              body: valueObject.MessageBody,
              sound: 'default',
          }
      };
      return admin.messaging().sendToDevice(tokens, payload);
  });
   });
  function loadUsers() {
  let dbRef = event.data.ref.parent.parent.ref('/GroupMembers/');
  let defer = new Promise((resolve, reject) =&gt; {
      dbRef.once('value', (snap) =&gt; {
          let data = snap.val();
          let users = [];
          for (var property in data) {
              users.push(data[property]);
          }
          resolve(users);
      }, (err) =&gt; {
          reject(err);
      });
  });
  return defer;
  </code></pre>
  
  <p>}</p>