Saturday 18 March 2017

Firebase CloudFunctions: Querying Nodes

I am exploring Cloud Functions with FCM to do a push notification to my iOS app device. I have the following structure and I am listening for people who registered to an event. I want to extract the eventHost so that I can go to my users node to find the userUID and eventually his deviceID, and send a push notification to him.

{
  "events" : {
    "XXX" : {
      "eventHost" : "YYY",
      "eventID" : "XXX",
      "registered" : {  //<-- Listening for this node
        "ASKDJHAIUCHA" : {
          "name" : "Emma Watson",
          "userUID" : "ASKDJHAIUCHA" //<-- How do I get this node?
        }
      },
    },

  },

  "users" : {
    "YYY" : {
      "deviceID" : "1234456",
      "name" : "Andrew Garfield",
      "userUID" : "YYY"
    },
  }
}

My code for the Cloud Functions as such so far:

exports.sendNotification = functions.database.ref('/events/{eventId}/registered')
    .onWrite(event => {
      const register = event.data.val();
      const eventHost = functions.database.ref('/events/' + event.params.eventId + '/eventHost')
      console.log('sendNotifications', eventHost);

      const payload = {
        notification: {
            title: "Event Registration",
            body: "Someone registered to your event!"
        }
      };

      const options = {
        priority: "high"
      };

      return admin.messaging().sendToDevice("theDeviceID", payload, options)

    });

And my Swift portion when adding value into the database is as such:

@IBAction func registerButtonDidTap(_ sender: Any) {

        let personDict = [FIRConstants.UserInfo.Name: user.userName,
                          FIRConstants.UserInfo.UserUID: user.userUID]
        let registerPerson = [user.userUID!: personDict as AnyObject] as [String: AnyObject]
        let values = ["registered": registerPerson]

        FIRHelperClient.sharedInstance.checkIfEventHasRegistrants(ref, event.eventID!) { (has, error) in
            if let error = error {
                print(error.localizedDescription)
            } else {
                if let has = has {
                    if has {
                        self.ref.child("events").child(self.event.eventID!).child("registered").updateChildValues(registerPerson)

                    } else {
                        self.ref.child("events").child(self.event.eventID!).updateChildValues(values)

                    }
                }
            }
        }
    }

My cloud functions is definitely not complete as currently I am hardcoding theDeviceID. As I am pretty inexperience with Node.js and am trying to write both the iOS code in Swift and the server side code, so pls pardon me if this question is elementary. Some advice here would be helpful, thanks.



via Koh

No comments:

Post a Comment