Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pencilcheck/e7276b13a5526d52c7745b3c36e87da3 to your computer and use it in GitHub Desktop.
Save pencilcheck/e7276b13a5526d52c7745b3c36e87da3 to your computer and use it in GitHub Desktop.
// https://documentation.onesignal.com/reference#create-notification
var request = require('request');
var Promise = require("bluebird");
// email, templateId are required
module.exports = async function (email, templateId, payload) {
var message = '', heading = '', subtitle = '';
var restKey = process.env.ONE_SIGNAL_REST_KEY;
var appID = process.env.ONE_SIGNAL_APP_ID;
var body = {
'app_id': appID,
'template_id': templateId,
'filters': [
{
"field": "email",
"value": email
},
]
}
if (payload) {
message = payload.message || message
heading = payload.heading || heading
subtitle = payload.subtitle || subtitle
// Optional parameters shouldn't appear in body
// But if provided, it cannot be empty
body = Object.assign({}, body, {
'contents': { en: message }, // message
'headings': { en: heading }, // title
'subtitle': { en: subtitle }, // subtitle
})
}
return await new Promise((resolve, reject) => {
request({
method: 'POST',
uri: 'https://onesignal.com/api/v1/notifications',
headers: {
"authorization": `Basic ${restKey}`,
"content-type": "application/json"
},
json: true,
body
},
function (error, response, body) {
if (!error && !body.errors) {
console.log(body);
resolve(body)
} else {
console.error('Error:', error, body.errors);
reject([error, body.errors])
}
});
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment