Created
July 24, 2014 09:01
-
-
Save kjunine/958498ea441cb51e1f12 to your computer and use it in GitHub Desktop.
GCM Push using node-gcm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var gcm = require('node-gcm'), | |
Q = require('q'), | |
config = localrequire.config(), | |
User = localrequire.service('user'); | |
if (process.env.NODE_ENV === 'production') { | |
var sender = new gcm.Sender(config.gcm.key); | |
var getRegistrationIds = function(user) { | |
return User.preload(user) | |
.then(function(user) { | |
return user.device.android.registration_ids; | |
}); | |
}; | |
var sendMessage = function(registrationIds, type, data) { | |
var message = { | |
collapseKey: type, | |
delayWhileIdle: true, | |
timeToLive: 60, | |
dryRun: false, | |
data: { | |
title: 'StudyGPS', | |
message: 'You \'ve got a message.' | |
} | |
}; | |
message.data[type] = data; | |
var deferred = Q.defer(); | |
sender.send(message, registrationIds, 3, function(err, result) { | |
if (err) return deferred.reject(err); | |
else return deferred.resolve(result); | |
}); | |
return deferred.promise; | |
}; | |
exports.send = function(user, type, data) { | |
return getRegistrationIds(user) | |
.then(function(registrationIds) { | |
if (registrationIds && registrationIds.length > 0) { | |
return sendMessage(registrationIds, type, data); | |
} else { | |
return 'No registration ids for User:' + user + '.'; | |
} | |
}) | |
.catch(function(err) { | |
console.error('err on push:', err); | |
}); | |
}; | |
} else { | |
exports.send = function() {}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment