Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase push notifications - node worker

I need to send iOS push notifications to user whenever a certain child is added to a Firebase path.

I was thinking, that the best way to do that, would be to make a Node.js worker on Heroku, that would listen for changes and send a notification using Urban Airship.

I'm not sure what the best way is to listen for changes on Firebase from a Node.js worker on Heroku is. I'm not that familiar with heroku workers and Node.js.

Can anyone give me some pointers? Examples?

like image 503
Holger Sindbaek Avatar asked Feb 24 '15 00:02

Holger Sindbaek


1 Answers

Sending push notifications with Firebase and node-apn is easy:

var apn = require("apn");
var Firebase = require("firebase");

// true for production pipeline
var service = new apn.connection({ production: false }); 

// Create a reference to the push notification queue
var pushRef = new Firebase("<your-firebase>.firebaseio.com/notificationQueue");
// listen for items added to the queue
pushRef.on("child_added", function(snapshot) {

    // This location expects a JSON object of:
    // {
    //     "token": String - A user's device token
    //     "message": String - The message to send to the user
    // }
    var notificationData = snapshot.val();
    sendNotification(notificationData);
    snapshot.ref().remove();

});

function sendNotification(notificationData) {
    var notification = new apn.notification();
    // The default ping sound
    notification.sound = "ping.aiff";
    // Your custom message
    notification.alert = notificationData.message;
    // Send the notification to the specific device token
    service.pushNotification(notification, [notificationData.token]);
    // Clean up the connection
    service.shutdown();
}

For hosting this script, you won't be able to use a PaaS like Heroku. They tend to kill idle sockets. Instead you'll have to use a virtual machine.

Google Cloud Platform has a Node.js launcher that works well.

like image 56
David East Avatar answered Oct 19 '22 07:10

David East