Commit e81d30ee authored by ='s avatar =

initial release

parent 2d6b1dc7
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/onesignal-node.iml" filepath="$PROJECT_DIR$/.idea/onesignal-node.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PreferredVcsStorage">
<preferredVcsName>Git</preferredVcsName>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
This diff is collapsed.
MIT License
Copyright (c) 2017 Kolektif Labs
Copyright (c) 2017 fxgx
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
# onesignal-node
A Node.js Library for OneSignal push notification service
A Node.js client library for [OneSignal](https://onesignal.com/) API.
## Table of Contents
* [Installation](#installation)
* [Usage](*usage)
* [Creating a service client](#creating-a-client)
* [Sending a push notification](#sending-push-notifications)
* [Canceling a push notification](#canceling-a-push-notification)
## Installation
```
npm install onesignal-node --save
```
##Usage
``` js
var OneSignal = require('onesignal-node');
```
### Creating a client
You can create a OneSignal Client as shown below. It takes a JSON object as parameter which
contains your OneSignal API credentials.
``` js
// create a Client for a single app
var myClient = new OneSignal.Client({
userAuthKey: 'XXXXXX',
// note that "app" must have "appAuthKey" and "appId" keys
app: { appAuthKey: 'XXXXX', appId: 'XXXXX' }
});
```
You can also create a Client for multiple Apps
``` js
// create a Client for a multiple apps
var myClient = new OneSignal.Client({
userAuthKey: 'XXXXXX',
apps: ['id1', 'id2'] // your app ids
});
```
You can always create a Client with no credential and set them later:
``` js
// create a Client for a multiple apps
var myClient = new OneSignal.Client({});
myClient.userAuthKey = 'XXXXXX';
myClient.app = { appAuthKey: 'XXXXX', appId: 'XXXXX' };
// or
myClient.setApp({ appAuthKey: 'XXXXX', appId: 'XXXXX' });
myClient.apps = ['id1', 'id2', 'id3']; // this will override "app"
```
### Creating new notification object
We will pass Notification objects to Client to send them.
``` js
// contents is REQUIRED unless content_available=true or template_id is set.
var firstNotification = OneSignal.Notification({
contents: {
en: "Test notification",
tr: "Test mesajı"
}
});
```
You can also create a Notification object without contents:
``` js
var firstNotification = OneSignal.Notification({
content_available: true
});
// or if you want to use template_id instead:
var firstNotification = OneSignal.Notification({
template_id: "be4a8044-bbd6-11e4-a581-000c2940e62c"
});
```
You can set filters, data, buttons and all of the fields available on [OneSignal Documentation](https://documentation.onesignal.com/reference#create-notification)
by using `.setParameter(paramName, paramValue)` function:
``` js
firstNotification.setParameter('data', {"abc": "123", "foo": "bar"});
firstNotification.setParameter('headings', {"en": "English Title", "es": "Spanish Title"});
```
### Sending Push Notifications
Sending a notification using using Segments:
``` js
var OneSignal = require('../lib');
// first we need to create a client
var myClient = new OneSignal.Client({
userAuthKey: 'XXXXXX',
app: { appAuthKey: 'XXXXX', appId: 'XXXXX' }
});
// we need to create a notification to send
var firstNotification = OneSignal.Notification({
contents: {
en: "Test notification",
tr: "Test mesajı"
}
});
// set target users
firstNotification.setIncludedSegments(['All Users']);
firstNotification.setExcludedSegments(['Inactive Users']);
// set notification parameters
firstNotification.setParameter('data', {"abc": "123", "foo": "bar"});
firstNotification.setParameter('send_after', 'Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)');
// send this notification to All Users except Inactive ones
myClient.sendNotification(firstNotification, function (err, httpResponse,data) {
if (err) {
console.log('Something went wrong...');
} else {
console.log(data);
}
});
```
To send a notification based on filters, use `.setFilter(filters)` method:
``` js
firstNotification.setFilters([
{"field": "tag", "key": "level", "relation": ">", "value": "10"},
{"field": "amount_spent", "relation": ">","value": "0"}
]);
```
To send specific devices use `.setTargetDevices(include_player_ids)` method:
``` js
firstNotification.setTargetDevices(["1dd608f2-c6a1-11e3-851d-000c2940e62c",
"2dd608f2-c6a1-11e3-851d-000c2940e62c"]);
```
Note that `.sendNotification(notification, callback)` function will send the notification to
the `app` specified during the creation of Client object. If you want to send notification
tp multiple apps, you must set `apps` array instead, on Client object:
``` js
myClient.apps = apps: ['id1', 'id2'];
```
### Canceling a push notification
You can cancel a notification simply by calling `.cancel`
``` js
// this will cancel the notification for current app (myClient.app)
myClient.cancelNotification('notificationId', function (err, httpResponse, data) {
if (err) {
}
})
```
##License
This project is under the MIT license.
\ No newline at end of file
'use strict';
var request = require('request');
var constants = require('./constants');
var ALLOWED_CREDENTIALS = [
{ name: 'userAuthKey', type: 'string' },
{ name: 'app', type: 'object', requiredFields: ['appAuthKey', 'appId'] },
{ name: 'apps', type: 'object'}
];
/**
* make a basic request
* @param url
* @param apiKey
* @param method : [ GET, POSt, PUT ...]
* @param body
* @param callback (err, httpResponse, body)
*/
var basicRequest = function (url, apiKey, method, body, callback) {
var options = {
url: url,
method: method
};
if (apiKey) {
options.headers = {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Basic ' + apiKey
}
}
if (body) {
options.body = body;
options.json = true;
}
request(options, callback);
};
var checkCredential = function (credentialName, credential) {
for (var i = 0; i < ALLOWED_CREDENTIALS.length; i++) {
if (ALLOWED_CREDENTIALS[i].name === credentialName) {
if (typeof credential !== ALLOWED_CREDENTIALS[i].type) {
throw credentialName + ' must be a ' + ALLOWED_CREDENTIALS[i].type;
}
if (ALLOWED_CREDENTIALS[i].requiredFields) {
for (var j = 0; j < ALLOWED_CREDENTIALS[i].requiredFields.length; j++) {
if (!(ALLOWED_CREDENTIALS[i].requiredFields[j] in credential)) {
throw credentialName + ' must contain ' + ALLOWED_CREDENTIALS[i].requiredFields[j]
}
}
}
return true;
}
}
return false;
};
/**
*
* @param credentials { JSON }
* @constructor
*/
var Client = function (credentials) {
if (typeof credentials !== 'object') {
throw 'credentials parameter must be a JSON object'
}
this.API_URI = constants.API_ROOT;
for (var key in credentials) {
if (credentials.hasOwnProperty(key) && checkCredential(key, credentials[key])) {
this[key] = credentials[key];
}
}
};
/**
*
* @param rootUrl { String } default 'https://onesignal.com/api/v1';
*/
Client.prototype.setRootUrl = function (rootUrl) {
if (!rootUrl) {
throw 'You must set a valid rootUsrl.'
}
this.API_URI = rootUrl;
};
/**
* set an app object
* @param app { JSON } {}
*/
Client.prototype.setApp = function (app) {
checkCredential('app', app);
this.app = app;
};
/**
* create a notification
* @param notification { Notification }
* @param callback
*/
Client.prototype.sendNotification = function (notification, callback) {
if (!notification || !notification.postBody) {
throw 'notification parameter must be a typeof Notification object.';
}
var postBody = notification.postBody;
if (this.apps && this.apps.length > 0) {
postBody.app_ids = this.apps;
basicRequest(this.API_URI + constants.NOTIFICATIONS_PATH, this.userAuthKey, 'POST', postBody, callback);
} else if (this.app) {
postBody.app_id = this.app.appId;
basicRequest(this.API_URI + constants.NOTIFICATIONS_PATH, this.app.appAuthKey, 'POST', postBody, callback);
} else {
throw 'You must set either an "app" or "apps" on Client';
}
};
/**
* Used to stop a scheduled or currently outgoing notification.
* @param notificationId { String } Notification id
* @param callback
*/
Client.prototype.cancelNotification = function (notificationId, callback) {
if (!this.app) {
throw 'You must define an "app" object.'
}
var notificationUri = this.API_URI + constants.NOTIFICATIONS_PATH + '/' + notificationId + '?app_id=' + this.app.appId;
basicRequest(notificationUri, this.app.appAuthKey, 'DELETE', null, callback);
};
/**
*
* @param notificationId { String }
* @param callback
*/
Client.prototype.viewNotification = function (notificationId, callback) {
if (!this.app) {
throw 'You must define an "app" object.'
}
var notificationUri = this.API_URI + constants.NOTIFICATIONS_PATH + '/' + notificationId + '?app_id=' + this.app.appId;
basicRequest(notificationUri, this.app.appAuthKey, 'GET', null, callback);
};
/**
*
* @param query { String } ex: limit:100&offset=9
* @param callback
*/
Client.prototype.viewNotifications = function (query, callback) {
if (!this.app) {
throw 'You must define an "app" object.'
}
var appUri = this.API_URI + constants.NOTIFICATIONS_PATH + '?app_id=' + this.app.appId + '&' + query;
basicRequest(appUri, this.app.appAuthKey, 'GET', null, callback);
};
/**
*
* @param callback
*/
Client.prototype.viewApps = function (callback) {
if (!this.userAuthKey) {
throw 'You must define "userAuthKey" on Client'
}
basicRequest(this.API_URI + constants.APPS_PATH, this.userAuthKey, 'GET', null, callback);
};
/**
*
* @param appId { String }
* @param callback
*/
Client.prototype.viewApp = function (appId, callback) {
if (!this.userAuthKey) {
throw 'You must define "userAuthKey" on Client'
}
basicRequest(this.API_URI + constants.APPS_PATH + '/' + appId, this.userAuthKey, 'GET', null, callback);
};
/**
*
* @param body { JSON }
* @param callback
*/
Client.prototype.createApp = function (body, callback) {
if (!body.name) {
throw 'You must specify a name in body';
}
basicRequest(this.API_URI + constants.APPS_PATH, this.userAuthKey, 'POST', body, callback);
};
/**
* Updates currently defined app
* @param body { JSON }
* @param callback
*/
Client.prototype.updateApp = function (body, callback) {
if (!this.app) {
throw 'You must define an "app" object.'
}
basicRequest(this.API_URI + constants.APPS_PATH + '/' + this.app.appId, this.userAuthKey, 'PUT', body, callback);
};
/**
*
* @param query { String } ex: limit=200&offset=10
* @param callback
*/
Client.prototype.viewDevices = function (query, callback) {
if (!this.app) {
throw 'You must define an "app" object.'
}
var viewUri = this.API_URI + constants.DEVICES_PATH + '?app_id=' + this.app.appId + '&' + query;
basicRequest(viewUri, this.app.appAuthKey, 'GET', null, callback);
};
/**
*
* @param deviceId { String }
* @param callback
*/
Client.prototype.viewDevice = function (deviceId, callback) {
var viewUri = this.API_URI + constants.DEVICES_PATH + '/' + deviceId + '?app_id=' + this.app.appId;
basicRequest(viewUri, null, 'GET', null, callback);
};
/**
*
* @param body { JSON }
* @param callback
*/
Client.prototype.addDevice = function (body, callback) {
basicRequest(this.API_URI + constants.DEVICES_PATH, null, 'POST', body, callback);
};
/**
*
* @param body { JSON }
* @param callback
*/
Client.prototype.editDevice = function (body, callback) {
basicRequest(this.API_URI + constants.DEVICES_PATH, null, 'PUT', body, callback);
};
module.exports = Client;
var Constants = {
API_ROOT: 'https://onesignal.com/api/v1',
/** PATHS **/
NOTIFICATIONS_PATH: '/notifications',
APPS_PATH: '/apps',
DEVICES_PATH: '/players'
};
module.exports = Constants;
var Client = require('./client');
var Notification = require('./notification');
module.exports = {
Client: Client,
Notification: Notification
};
'use strict';
var ALLOWED_FIELDS = ['contents', 'included_segments', 'excluded_segments', 'filters', 'include_player_ids',
'app_id', 'app_ids', 'headings', 'subtitle', 'template_id', 'content_available', 'mutable_content',
'data', 'url', 'ios_attachments', 'big_picture', 'adm_big_picture', 'chrome_big_picture', 'buttons',
'web_buttons', 'ios_category', 'send_after', 'delayed_option', 'delivery_time_of_day', 'ttl', 'priority',
'android_group', 'android_group_message', 'adm_group', 'adm_group_message', 'isIos', 'isAndroid',
'isAnyWeb', 'isChromeWeb', 'isFirefox', 'isSafari', 'isWP', 'isWP_WNS', 'isAdm', 'isChrome'];
/**
*
* @param initialBody The body must include either one of these: contents, content_available, template_id
* @constructor
*/
var Notification = function (initialBody) {
if (typeof initialBody !== 'object') {
throw 'Body must be a JSON object';
}
this.postBody = {};
if ('contents' in initialBody) {
this.postBody.contents = initialBody.contents;
} else if ('content_available' in initialBody){
this.postBody.content_available = initialBody.content_available;
} else if ('template_id' in initialBody) {
this.postBody.template_id = initialBody.template_id;
} else {
throw 'Body must include one of the following fields: contents, content_available, template_id'
}
};
/**
* set a parameter of notification body
* @param name
* @param value
*/
Notification.prototype.setParameter = function (name, value) {
if (name && name[0] === '!') {
name = name.substring(1);
} else if (ALLOWED_FIELDS.indexOf(name) === -1) {
throw '"' + name + '" is not present in documentation. You should add a ' +
'exclamation mark to the begging of the name, if you want to set it : !' + name;
}
this.postBody[name] = value;
};
/**
*
* @param contents
*/
Notification.prototype.setContent = function (contents) {
this.postBody.contents = contents;
};
/**
*
* @param included_segments The segment names you want to target
*/
Notification.prototype.setIncludedSegments = function (included_segments) {
this.postBody.included_segments = included_segments;
};
/**
*
* @param excluded_segments Segment that will be excluded when sending
*/
Notification.prototype.setExcludedSegments = function (excluded_segments) {
this.postBody.excluded_segments = excluded_segments;
};
/**
*
* @param filters
*/
Notification.prototype.setFilters = function (filters) {
this.postBody.filters = filters;
};
/**
*
* @param include_player_ids Specific players to send your notification to
*/
Notification.prototype.setTargetDevices = function (include_player_ids) {
this.postBody.include_player_ids = include_player_ids;
};
module.exports = Notification;
This diff is collapsed.
{
"name": "onesignal-node",
"version": "0.0.1",
"description": "A Node.js Library for OneSignal push notification service",
"main": "./lib/index.js",
"scripts": {
"test": "mocha --reporter spec"
},
"repository": {
"type": "git",
"url": "git+https://github.com/KolektifLabs/onesignal-node.git"
},
"keywords": [
"onesignal",
"one-signal",
"gcm",
"signal",
"notification"
],
"author": "Zeynel <zeynel.fxgx@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/KolektifLabs/onesignal-node.git/issues"
},
"homepage": "https://github.com/KolektifLabs/onesignal-node.git#readme",
"devDependencies": {
"chai": "^4.1.0",
"mocha": "^3.4.2"
},
"dependencies": {
"request": "^2.81.0"
}
}
'use strict';
var expect = require('chai').expect;
var OneSignal = require('../lib');
// first we need to create a client
var myClient = new OneSignal.Client({
userAuthKey: 'XXXXXX',
app: { appAuthKey: 'XXXXX', appId: 'XXXXX' }
});
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment