Skip to content

Instantly share code, notes, and snippets.

@glemiere
Last active June 29, 2018 02:50
Show Gist options
  • Save glemiere/3486e39abff5cdc3f48d50f88074f0b7 to your computer and use it in GitHub Desktop.
Save glemiere/3486e39abff5cdc3f48d50f88074f0b7 to your computer and use it in GitHub Desktop.
Simple ES5 module to send notifications through OneSignal from a NodeJS Server.
/**********
NotificationsService.js
---------------
Simple module written in ES5 to send notifications through OneSignal server-side.
NotificationsService.send : Sends a notification with the given "notif" parameter.
---------------
Requires OneSignal API key :
https://onesignal.com/
**********/
// Headers of the request.
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
};
// request options
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
// Request OneSignal to send a notification
var req = https.request(options, function(res) {
res.on('data', function(data) {
if (notif.data.infos && notif.data.infos.userid) {
var subject = notif.data.name.substring(0, notif.data.name.indexOf(':'));
// Checking if a notification of this type exist in database for this user.
UsersNotifications.findOne({
userid:notif.data.infos.userid,
subject:subject
}).exec(function (err, notification) {
// If it doesn't, create the record.
if (!err && !notification) {
UsersNotifications.create({
userid:notif.data.infos.userid,
subject:subject,
value:1
}).exec(function (err, finn) {
if (err) console.log(err);
});
}
// If it exists, increment the value.
else if (!err && notification) {
notification.value++;
UsersNotifications.update(notification.id, notification).exec(function (err, finn) {
if (err) console.log(err);
});
}
});
}
});
});
module.exports = {
/**
* Creates a notification based on the given infos
* @param notif
*/
send : function(notif) {
req.on('error', function(e) {
console.log("ERROR:", e);
});
req.write(JSON.stringify(notif));
req.end();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment