",
- headers: {
- "X-Customer-Campaign-ID": "christmas_campaign"
- },
- text: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}",
- html: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n
Hurry, this offer is only to {{customer_type}}\n
{{sender}}
"
- }
- }
-};
-
-client.transmissions.send(reqOpts, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log("Congrats you can use our SDK!");
- }
-});
diff --git a/examples/transmissions/send_transmission_with_bcc.js b/examples/transmissions/send_transmission_with_bcc.js
deleted file mode 100644
index 1b99388..0000000
--- a/examples/transmissions/send_transmission_with_bcc.js
+++ /dev/null
@@ -1,48 +0,0 @@
-"use strict";
-
-var key = "YOURAPIKEY"
- , SparkPost = require("sparkpost")
- , client = new SparkPost(key);
-
-var reqOpts = {
- transmissionBody: {
- recipients: [
- {
- address: {
- email: "original.recipient@example.com",
- name: "Original Recipient"
- },
- substitution_data: {
- recipient_type: "Original"
- }
- },
- {
- address: {
- email: "bcc.recipient@example.com",
- header_to: "'Original Recipient' "
- },
- substitution_data: {
- recipient_type: "BCC"
- }
- }
- ],
- content: {
- from: {
- name: "Node BCC Test",
- email: "from@example.com"
- },
- subject: "Example email using bcc",
- text: "An example email using bcc with SparkPost to the {{recipient_type}} recipient.",
- html: "An example email using bcc with SparkPost to the {{recipient_type}} recipient.
"
- }
- }
-};
-
-client.transmissions.send(reqOpts, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log("Congrats! You sent an email with bcc using SparkPost!");
- }
-});
diff --git a/examples/transmissions/send_transmission_with_cc.js b/examples/transmissions/send_transmission_with_cc.js
deleted file mode 100644
index 3485b01..0000000
--- a/examples/transmissions/send_transmission_with_cc.js
+++ /dev/null
@@ -1,52 +0,0 @@
-"use strict";
-
-var key = "YOURAPIKEY"
- , SparkPost = require("sparkpost")
- , client = new SparkPost(key);
-
-var reqOpts = {
- transmissionBody: {
- recipients: [
- {
- address: {
- email: "original.recipient@example.com",
- name: "Original Recipient"
- },
- substitution_data: {
- recipient_type: "Original"
- }
- },
- {
- address: {
- email: "cc.recipient@example.com",
- name: "Carbon Copy Recipient",
- header_to: "'Original Recipient' "
- },
- substitution_data: {
- recipient_type: "CC"
- }
- }
- ],
- content: {
- from: {
- name: "Node CC Test",
- email: "from@example.com"
- },
- headers: {
- "CC": "'Carbon Copy Recipient' "
- },
- subject: "Example email using cc",
- text: "An example email using cc with SparkPost to the {{recipient_type}} recipient.",
- html: "An example email using cc with SparkPost to the {{recipient_type}} recipient.
"
- }
- }
-};
-
-client.transmissions.send(reqOpts, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log("Congrats! You sent an email with cc using SparkPost!");
- }
-});
diff --git a/examples/transmissions/send_with_bcc.js b/examples/transmissions/send_with_bcc.js
new file mode 100644
index 0000000..e9d1804
--- /dev/null
+++ b/examples/transmissions/send_with_bcc.js
@@ -0,0 +1,58 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key)
+ , transmission = {
+ recipients: [
+ {
+ address: {
+ email: 'original.recipient@example.com',
+ name: 'Original Recipient'
+ },
+ substitution_data: {
+ recipient_type: 'Original'
+ }
+ },
+ {
+ address: {
+ email: 'bcc.recipient@example.com',
+ header_to: '"Original Recipient" '
+ },
+ substitution_data: {
+ recipient_type: 'BCC'
+ }
+ }
+ ],
+ content: {
+ from: {
+ name: 'Node BCC Test',
+ email: 'from@example.com'
+ },
+ subject: 'Example email using bcc',
+ text: 'An example email using bcc with SparkPost to the {{recipient_type}} recipient.',
+ html: 'An example email using bcc with SparkPost to the {{recipient_type}} recipient.
'
+ }
+ };
+
+// Promise
+client.transmissions.send(transmission)
+ .then(data => {
+ console.log(data);
+ console.log('Congrats! You sent an email with bcc using SparkPost!');
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.transmissions.send(transmission, function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats! You sent an email with bcc using SparkPost!');
+ console.log(data);
+ }
+});
diff --git a/examples/transmissions/send_with_cc.js b/examples/transmissions/send_with_cc.js
new file mode 100644
index 0000000..f7a09d8
--- /dev/null
+++ b/examples/transmissions/send_with_cc.js
@@ -0,0 +1,62 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key)
+ , transmission = {
+ recipients: [
+ {
+ address: {
+ email: 'original.recipient@example.com',
+ name: 'Original Recipient'
+ },
+ substitution_data: {
+ recipient_type: 'Original'
+ }
+ },
+ {
+ address: {
+ email: 'cc.recipient@example.com',
+ name: 'Carbon Copy Recipient',
+ header_to: '"Original Recipient" '
+ },
+ substitution_data: {
+ recipient_type: 'CC'
+ }
+ }
+ ],
+ content: {
+ from: {
+ name: 'Node CC Test',
+ email: 'from@example.com'
+ },
+ headers: {
+ 'CC': '"Carbon Copy Recipient" '
+ },
+ subject: 'Example email using cc',
+ text: 'An example email using cc with SparkPost to the {{recipient_type}} recipient.',
+ html: 'An example email using cc with SparkPost to the {{recipient_type}} recipient.
'
+ }
+ };
+
+// Promise
+client.transmissions.send(transmission)
+ .then(data => {
+ console.log('Congrats! You sent an email with cc using SparkPost!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.transmissions.send(transmission, function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats! You sent an email with cc using SparkPost!');
+ console.log(data);
+ }
+});
diff --git a/examples/transmissions/stored_recipients_inline_content.js b/examples/transmissions/stored_recipients_inline_content.js
deleted file mode 100644
index a087db5..0000000
--- a/examples/transmissions/stored_recipients_inline_content.js
+++ /dev/null
@@ -1,28 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key);
-
-var reqObj = {
- transmissionBody: {
- recipients: {
- list_id: 'example-list'
- },
- content: {
- from: 'From Envelope ',
- subject: 'Example Email for Stored List and Inline Content',
- html: 'Hello World
',
- text: 'Hello World!'
- }
- }
-};
-
-client.transmissions.send(reqObj, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/transmissions/stored_recipients_stored_content.js b/examples/transmissions/stored_recipients_stored_content.js
deleted file mode 100644
index 2609013..0000000
--- a/examples/transmissions/stored_recipients_stored_content.js
+++ /dev/null
@@ -1,27 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key);
-
-var reqOpts = {
- transmissionBody: {
- recipients: {
- list_id: 'example-list'
- },
- content: {
- from: 'From Envelope ',
- subject: 'Example Email for Stored List and Template',
- template_id: 'my-template'
- }
- }
-};
-
-client.transmissions.send(reqOpts, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/transmissions/stored_template_send.js b/examples/transmissions/stored_template_send.js
deleted file mode 100644
index 5189262..0000000
--- a/examples/transmissions/stored_template_send.js
+++ /dev/null
@@ -1,25 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key);
-
-var reqOpts = {
- transmissionBody: {
- campaignId: 'ricks-campaign',
- content: {
- template_id: 'ricks-template'
- },
- 'num_rcpt_errors': 3,
- recipients: [{ address: { email: 'rick.sanchez@rickandmorty100years.com', name: 'Rick Sanchez' } }]
- }
-};
-
-client.transmissions.send(reqOpts, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('What up my glib globs! SparkPost!');
- }
-});
diff --git a/examples/webhooks/create.js b/examples/webhooks/create.js
new file mode 100644
index 0000000..97b532c
--- /dev/null
+++ b/examples/webhooks/create.js
@@ -0,0 +1,38 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key)
+ , webhook = {
+ name: 'Test Webhook',
+ target: 'http://client.test.com/test-webhook',
+ auth_token: 'AUTH_TOKEN',
+ events: [
+ 'delivery',
+ 'injection',
+ 'open',
+ 'click'
+ ]
+ };
+
+// Promise
+client.webhooks.create(webhook)
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.create(webhook, function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ }
+});
diff --git a/examples/webhooks/create_webhook.js b/examples/webhooks/create_webhook.js
deleted file mode 100644
index 1d1b19d..0000000
--- a/examples/webhooks/create_webhook.js
+++ /dev/null
@@ -1,25 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key)
- , webhook = {
- name: 'Test webhook'
- , target: 'http://client.test.com/test-webhook'
- , auth_token: 'AUTH_TOKEN'
- , events: [
- 'delivery',
- 'injection',
- 'open',
- 'click'
- ]
- };
-
-client.webhooks.create(webhook, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/webhooks/delete.js b/examples/webhooks/delete.js
new file mode 100644
index 0000000..725e342
--- /dev/null
+++ b/examples/webhooks/delete.js
@@ -0,0 +1,27 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key);
+
+// Promise
+client.webhooks.delete('TEST_WEBHOOK_UUID')
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.delete('TEST_WEBHOOK_UUID', function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ }
+});
diff --git a/examples/webhooks/delete_webhook.js b/examples/webhooks/delete_webhook.js
deleted file mode 100644
index 95f75cf..0000000
--- a/examples/webhooks/delete_webhook.js
+++ /dev/null
@@ -1,14 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key);
-
-client.webhooks['delete']('TEST_WEBHOOK_UUID', function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/webhooks/describe_webhook.js b/examples/webhooks/describe_webhook.js
deleted file mode 100644
index 99e9020..0000000
--- a/examples/webhooks/describe_webhook.js
+++ /dev/null
@@ -1,18 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key)
- , options = {
- id: 'TEST_WEBHOOK_UUID'
- , timezone: 'America/New_York'
- };
-
-client.webhooks.describe(options, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/webhooks/get.js b/examples/webhooks/get.js
new file mode 100644
index 0000000..57cdbb6
--- /dev/null
+++ b/examples/webhooks/get.js
@@ -0,0 +1,30 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key)
+ , options = {
+ timezone: 'America/New_York'
+ };
+
+// Promise
+client.webhooks.get('TEST_WEBHOOK_UUID', options)
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.get('TEST_WEBHOOK_UUID', options, function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ }
+});
diff --git a/examples/webhooks/getBatchStatus.js b/examples/webhooks/getBatchStatus.js
index d527cc3..2826764 100644
--- a/examples/webhooks/getBatchStatus.js
+++ b/examples/webhooks/getBatchStatus.js
@@ -4,15 +4,27 @@ var key = 'YOURAPIKEY'
, SparkPost = require('sparkpost')
, client = new SparkPost(key)
, options = {
- id: 'TEST_WEBHOOK_UUID'
- , limit: 1000
+ limit: 1000
};
-client.webhooks.getBatchStatus(options, function(err, res) {
+// Promise
+client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', options)
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', options, function(err, data) {
if (err) {
+ console.log('Whoops! Something went wrong');
console.log(err);
} else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
+ console.log('Congrats you can use our client library!');
+ console.log(data);
}
});
diff --git a/examples/webhooks/getDocumentation.js b/examples/webhooks/getDocumentation.js
index d9acc9f..8319814 100644
--- a/examples/webhooks/getDocumentation.js
+++ b/examples/webhooks/getDocumentation.js
@@ -4,11 +4,24 @@ var key = 'YOURAPIKEY'
, SparkPost = require('sparkpost')
, client = new SparkPost(key);
-client.webhooks.getDocumentation(function(err, res) {
+// Promise
+client.webhooks.getDocumentation()
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.getDocumentation(function(err, data) {
if (err) {
+ console.log('Whoops! Something went wrong');
console.log(err);
} else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
+ console.log('Congrats you can use our client library!');
+ console.log(data);
}
});
diff --git a/examples/webhooks/getSamples.js b/examples/webhooks/getSamples.js
index 6930d77..3843865 100644
--- a/examples/webhooks/getSamples.js
+++ b/examples/webhooks/getSamples.js
@@ -7,11 +7,24 @@ var key = 'YOURAPIKEY'
events: 'bounce'
};
-client.webhooks.getSamples(options, function(err, res) {
+// Promise
+client.webhooks.getSamples(options)
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.getSamples(options, function(err, data) {
if (err) {
+ console.log('Whoops! Something went wrong');
console.log(err);
} else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
+ console.log('Congrats you can use our client library!');
+ console.log(data);
}
});
diff --git a/examples/webhooks/get_all_webhooks.js b/examples/webhooks/get_all_webhooks.js
deleted file mode 100644
index 3f36053..0000000
--- a/examples/webhooks/get_all_webhooks.js
+++ /dev/null
@@ -1,14 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key);
-
-client.webhooks.all(function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/webhooks/list.js b/examples/webhooks/list.js
new file mode 100644
index 0000000..10f4756
--- /dev/null
+++ b/examples/webhooks/list.js
@@ -0,0 +1,27 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key);
+
+// Promise
+client.webhooks.list()
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.list(function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ }
+});
diff --git a/examples/webhooks/update.js b/examples/webhooks/update.js
new file mode 100644
index 0000000..8c33443
--- /dev/null
+++ b/examples/webhooks/update.js
@@ -0,0 +1,34 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key)
+ , webhook = {
+ name: 'Renamed Test Webhook',
+ events: [
+ 'policy_rejection',
+ 'delay'
+ ]
+ };
+
+// Promise
+client.webhooks.update('TEST_WEBHOOK_UUID', webhook)
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.update('TEST_WEBHOOK_UUID', webhook, function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ }
+});
diff --git a/examples/webhooks/update_webhook.js b/examples/webhooks/update_webhook.js
deleted file mode 100644
index 05284c5..0000000
--- a/examples/webhooks/update_webhook.js
+++ /dev/null
@@ -1,22 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key)
- , webhook = {
- id: 'TEST_WEBHOOK_UUID'
- , name: 'Renamed Test webhook'
- , events: [
- 'policy_rejection',
- 'delay'
- ]
- };
-
-client.webhooks.update(webhook, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/examples/webhooks/validate.js b/examples/webhooks/validate.js
new file mode 100644
index 0000000..d1a312f
--- /dev/null
+++ b/examples/webhooks/validate.js
@@ -0,0 +1,32 @@
+'use strict';
+
+var key = 'YOURAPIKEY'
+ , SparkPost = require('sparkpost')
+ , client = new SparkPost(key)
+ , options = {
+ message: {
+ msys: {}
+ }
+ };
+
+// Promise
+client.webhooks.validate('TEST_WEBHOOK_UUID', options)
+ .then(data => {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ })
+ .catch(err => {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ });
+
+// Callback
+client.webhooks.validate('TEST_WEBHOOK_UUID', options, function(err, data) {
+ if (err) {
+ console.log('Whoops! Something went wrong');
+ console.log(err);
+ } else {
+ console.log('Congrats you can use our client library!');
+ console.log(data);
+ }
+});
diff --git a/examples/webhooks/validate_webhook.js b/examples/webhooks/validate_webhook.js
deleted file mode 100644
index 5b885ba..0000000
--- a/examples/webhooks/validate_webhook.js
+++ /dev/null
@@ -1,20 +0,0 @@
-'use strict';
-
-var key = 'YOURAPIKEY'
- , SparkPost = require('sparkpost')
- , client = new SparkPost(key)
- , options = {
- id: 'TEST_WEBHOOK_UUID'
- , message: {
- msys: {}
- }
- };
-
-client.webhooks.validate(options, function(err, res) {
- if (err) {
- console.log(err);
- } else {
- console.log(res.body);
- console.log('Congrats you can use our SDK!');
- }
-});
diff --git a/lib/Promise.js b/lib/Promise.js
new file mode 100644
index 0000000..7bf5c2c
--- /dev/null
+++ b/lib/Promise.js
@@ -0,0 +1,31 @@
+'use strict';
+
+/**
+ * asCallback method mimics bluebird and allows
+ * promise object to handle an optional nodeback
+ *
+ * @param cb {Function}
+ * @return Promise
+ *
+ * @example
+ * function eitherOr(options, callback) {
+ * return promiseThingy(options).asCallback(callback);
+ * }
+ */
+Promise.prototype.asCallback = function(cb) {
+ if (typeof cb !== 'function') {
+ cb = noop;
+ }
+
+ return this.then((result) => {
+ cb(null, result);
+ return this;
+ }).catch((err) => {
+ cb(err);
+ return this;
+ });
+};
+
+function noop() {}
+
+module.exports = Promise;
diff --git a/lib/SendGridCompatibility/Email.js b/lib/SendGridCompatibility/Email.js
deleted file mode 100644
index a523122..0000000
--- a/lib/SendGridCompatibility/Email.js
+++ /dev/null
@@ -1,102 +0,0 @@
-'use strict';
-
-/**
- * Email object constructor
- *
- * @param options object that contains initial values
- */
-function Email(options){
- for (var option in options) {
- this[option] = options[option];
- }
-}
-
-/**
- * SendGrid email compatibility functions
- *
- * @param Most have a single value to map
- * Add functions will often contain a key / value pair
- */
-Email.prototype.addTo = function (address){
- if (this.to === undefined){
- this.to = address;
- } else if (typeof this.to === 'string'){
- this.to = [this.to];
- this.to.push(address);
- } else {
- this.to.push(address);
- }
-};
-Email.prototype.setFrom = function (address){
- this.from = address;
-};
-Email.prototype.setSubject = function (subject){
- this.subject = subject;
-};
-Email.prototype.setText = function (text){
- this.text = text;
-};
-Email.prototype.setHtml = function (html){
- this.html = html;
-};
-Email.prototype.addHeader = function (key, value){
- if (this.headers === undefined){
- this.headers = {};
- }
- this.headers[key] = value;
-};
-Email.prototype.setHeaders = function (headers){
- this.headers = headers;
-};
-Email.prototype.addSubstitution = function (key, value){
- if (this.sub === undefined){
- this.sub = {};
- }
- if (typeof value === 'string'){
- this.sub[key] = [value];
- } else {
- this.sub[key] = value;
- }
-};
-Email.prototype.setSubstitutions = function (substitutions){
- this.sub = substitutions;
-};
-Email.prototype.addSection = function (key, value){
- if (this.section === undefined){
- this.section = {};
- }
- this.section[key] = value;
-};
-Email.prototype.setSections = function (sections){
- this.section = sections;
-};
-// SparkPost doesn't currently support addUniqueArg, throw an error
-Email.prototype.addUniqueArg = function (){
- throw new Error('Unique Argument compatibility is not supported.');
-};
-// SparkPost doesn't currently support setUniqueArgs, throw an error
-Email.prototype.setUniqueArgs = function (){
- throw new Error('Unique Argument compatibility is not supported.');
-};
-// SparkPost doesn't currently support addCategory, throw an error
-Email.prototype.addCategory = function (){
- throw new Error('Category compatibility is not supported.');
-};
-// SparkPost doesn't currently support setCategories, throw an error
-Email.prototype.setCategories = function (){
- throw new Error('Category compatibility is not supported.');
-};
-// SparkPost doesn't currently support addFilter, throw an error
-Email.prototype.addFilter = function (){
- throw new Error('Filter compatibility is not supported.');
-};
-// SparkPost doesn't currently support setFilters, throw an error
-Email.prototype.setFilters = function (){
- throw new Error('Filter compatibility is not supported.');
-};
-// SparkPost doesn't currently support addFile, throw an error
-Email.prototype.addFile = function (){
- throw new Error('File compatibility is not supported.');
-};
-
-module.exports = Email;
diff --git a/lib/SendGridCompatibility/index.js b/lib/SendGridCompatibility/index.js
deleted file mode 100644
index b5d605e..0000000
--- a/lib/SendGridCompatibility/index.js
+++ /dev/null
@@ -1,127 +0,0 @@
-'use strict';
-var _ = require('lodash');
-var url = require('url');
-var SparkPost = require('../sparkpost');
-
-/**
- * SendGrid compatibility constructor
- * Responsible for taking the api key and config options and
- * translating them into a format compatible with SparkPost's
- * options.
- *
- * @param username: dropped SendGrid username string
- * @param apiKey: api key string
- * @param options: optional additional options object
- */
-var sendgrid = function(username, apiKey, options) {
- options = options || {};
- var urlOpts = {
- protocol: options.protocol
- , hostname: options.host
- , port: options.port
- }
- , opts = {
- endpoint: url.format(urlOpts)
- };
-
- this.client = new SparkPost(apiKey, opts);
-};
-
-/**
- * Private Method for translating a user's SendGrid substitutions and sections
- * to a consolidated SparkPost substitutionData object
- *
- * @param payload: SendGrid formatted object or SendGrid Email object to
- * be translated into a SparkPost payload
- * @returns object: substitutionData object as per SparkPost payload format
- */
-var consolidateSubstitutionData = function(payload) {
- var substitutionData = {};
- if (payload.sub !== undefined && payload.section !== undefined){
- substitutionData = _.merge(payload.sub, payload.section);
- } else if (payload.sub !== undefined){
- substitutionData = payload.sub;
- } else if (payload.section !== undefined){
- substitutionData = payload.section;
- }
- return substitutionData;
-};
-
-/**
- * Private Method for translating a user's SendGrid to and toname to a recipients
- * array that the transmissions "Class" can understand
- *
- * @param payload: SendGrid formatted object or SendGrid Email object to
- * be translated into a SparkPost payload
- * @returns array: recipients array as per SparkPost payload format
- */
-var parseTo = function(payload){
- var recipients = [];
- if (typeof payload.to === 'string'){
- payload.to = [payload.to];
- }
- for (var i = 0; payload.to.length > i; i++){
- var to = {
- address: {
- email: payload.to[i]
- }
- };
- if (payload.toname !== undefined && payload.toname[i] !== undefined){
- to.address.name = payload.toname[i];
- }
- recipients.push(to);
- }
- return recipients;
-};
-
-/**
- * Private Method for translating a user's SendGrid payload to a format
- * that the transmissions "Class" can understand
- *
- * @param payload: SendGrid formatted object or SendGrid Email object to
- * be translated into a SparkPost payload
- * @returns object: translation from SendGrid payload to SparkPost payload
- */
-var translatePayload = function(payload) {
- var sub = consolidateSubstitutionData(payload)
- , input = {
- recipients: [],
- from: '',
- html: '',
- text: '',
- subject: ''
- };
-
- if (payload.to !== undefined){
- input.recipients = parseTo(payload);
- }
- input.from = payload.from;
- if (payload.fromname !== undefined){
- input.from = input.from + ' <' + payload.fromname + '>';
- }
- input.subject = payload.subject;
- input.text = payload.text;
- input.html = payload.html;
- input.replyTo = payload.replyto;
- input.customHeaders = payload.headers;
- input.substitutionData = (Object.keys(sub).length > 0) ? sub : undefined;
-
- return input;
-};
-
-/**
- * An exposed function of SendGridCompatibility that calls upon
- * private helper methods to translate an Email or inline object
- * and then pass that content to the transmissions send function.
- *
- * @param payload: SendGrid formatted object or SendGrid Email object to
- * be translated into a SparkPost payload and sent
- */
-sendgrid.prototype.send = function(payload, callback) {
- var translated = translatePayload(payload);
- this.client.transmissions.send({transmissionBody: translated }, callback);
-};
-
-sendgrid.prototype.Email = require('./Email');
-
-module.exports = sendgrid;
diff --git a/lib/inboundDomains.js b/lib/inboundDomains.js
index 56e27c3..a44485b 100644
--- a/lib/inboundDomains.js
+++ b/lib/inboundDomains.js
@@ -1,67 +1,79 @@
'use strict';
-var api = 'inbound-domains';
+const api = 'inbound-domains';
+const Promise = require('./Promise');
module.exports = function(client) {
- var inboundDomains = {
- all: function(callback) {
+ return {
+ /**
+ * List an overview of all inbound domains in the account.
+ *
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ list: function(callback) {
var options = {
uri: api
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- find: function(domain, callback) {
- if(typeof domain === 'function') {
- callback = domain;
- domain = null;
- }
+ /**
+ * Get an inbound domain by its domain name
+ *
+ * @param {string} domain
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ get: function(domain, callback) {
+ let options;
- if(!domain) {
- callback(new Error('domain is required'));
- return;
+ if (!domain || typeof domain !== 'string') {
+ return Promise.reject(new Error('domain is required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api + '/' + domain
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- create: function(domain, callback) {
- if(typeof domain === 'function') {
- callback = domain;
- domain = null;
- }
+ /**
+ * Create a new inbound domain
+ *
+ * @param {Object} createOpts
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ create: function(createOpts, callback) {
+ let options;
- if(!domain) {
- callback(new Error('domain is required'));
- return;
+ if (!createOpts || typeof createOpts !== 'object') {
+ return Promise.reject(new Error('create options are required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api
- , json: {
- domain: domain
- }
+ , json: createOpts
};
- client.post(options, callback);
+ return client.post(options, callback).asCallback(callback);
},
+ /**
+ * Delete an existing inbound domain
+ *
+ * @param {string} domain
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
delete: function(domain, callback) {
- if (typeof domain === 'function') {
- callback = domain;
- domain = null;
- }
+ let options;
- if (!domain) {
- callback(new Error('domain is required'));
- return;
+ if (!domain || typeof domain !== 'string') {
+ return Promise.reject(new Error('domain is required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api + '/' + domain
};
- client.delete(options, callback);
+ return client.delete(options).asCallback(callback);
}
};
-
- return inboundDomains;
};
diff --git a/lib/messageEvents.js b/lib/messageEvents.js
index e46f763..096cd67 100644
--- a/lib/messageEvents.js
+++ b/lib/messageEvents.js
@@ -1,37 +1,34 @@
'use strict';
-var api = 'message-events';
+const api = 'message-events';
/*
* "Class" declaration, Message Events API exposes one function:
* - search: retrieves list of message events according to given params
*/
-module.exports = function (client) {
+module.exports = function(client) {
return {
+ /**
+ * Search for message events using given parameters
+ *
+ * @param {Object} parameters
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
search: function(parameters, callback) {
- var arrayParams = [
- 'bounce_classes',
- 'campaign_ids',
- 'events',
- 'friendly_froms',
- 'message_ids',
- 'recipients',
- 'template_ids',
- 'transmission_ids'
- ]
- , options;
+ var options = {
+ uri: api
+ , qs: {}
+ };
- arrayParams.forEach(function(paramname) {
+ Object.keys(parameters).forEach(function(paramname) {
if (Array.isArray(parameters[paramname])) {
- parameters[paramname] = parameters[paramname].toString();
+ options.qs[paramname] = parameters[paramname].join(',');
+ } else {
+ options.qs[paramname] = parameters[paramname];
}
});
-
- options = {
- uri: api
- , qs: parameters
- };
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
}
};
};
diff --git a/lib/recipientLists.js b/lib/recipientLists.js
index cfa80e4..1644038 100644
--- a/lib/recipientLists.js
+++ b/lib/recipientLists.js
@@ -1,97 +1,138 @@
'use strict';
-var api = 'recipient-lists'
- , toApiFormat = require('./toApiFormat');
+const Promise = require('./Promise');
+const api = 'recipient-lists';
module.exports = function(client) {
- var recipientLists = {
- all: function(callback) {
+ return {
+ /**
+ * Get a list of all your recipient lists
+ * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-retrieve-get
+ *
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ list: function(callback) {
var reqOpts = {
uri: api
};
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- find: function(options, callback) {
+
+ /**
+ * Get a list of all your recipient lists
+ * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-list-get
+ *
+ * @param {string} id - Unique ID of the list to return
+ * @param {Object} options - Hash of request options
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ get: function(id, options, callback) {
+ var reqOpts;
options = options || {};
- if(!options.id) {
- callback(new Error('id is required'));
- return;
+ // Handle optional options argument
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
}
- var reqOpts = {
- uri: api + '/' + options.id
- };
-
- if(options.show_recipients) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.show_recipients = options.show_recipients;
+ if (!id) {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- client.get(reqOpts, callback);
- },
- create: function(options, callback) {
- options = options || {};
+ reqOpts = {
+ uri: api + '/' + id,
+ qs: options
+ };
- if(!options.recipients) {
- callback(new Error('recipients list is required'));
- return;
- }
+ return client.get(reqOpts).asCallback(callback);
+ },
- var reqOpts = {
- uri: api
- };
- if (options.num_rcpt_errors) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors;
- delete options.num_rcpt_errors;
+ /**
+ * Create a new recipient list
+ * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-create-post
+ *
+ * @param {Object} recipientList - recipient list object
+ * @param {Array} recipientList.recipients - Array of recipient objects
+ * @param {RequestCb} callback
+ * @return {Promise}
+ */
+ create: function(recipientList, callback) {
+ var reqOpts;
+
+ if (!recipientList || typeof recipientList !== 'object' || !recipientList.recipients) {
+ return Promise.reject(new Error('recipient list is required')).asCallback(callback);
}
- reqOpts.json = toApiFormat(options);
+ reqOpts = {
+ uri: api,
+ json: recipientList,
+ qs: {
+ num_rcpt_errors: recipientList.num_rcpt_errors
+ }
+ };
- client.post(reqOpts, callback);
+ return client.post(reqOpts).asCallback(callback);
},
- update: function(options, callback) {
- options = options || {};
- if(!options.id) {
- callback(new Error('recipients list id is required'));
- return;
+ /**
+ * Update an existing list
+ * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-update-put
+ *
+ * @param {string} id - Unique ID of the list to be updated
+ * @param {Object} recipientList - recipient list object
+ * @param {Array} recipientList.recipients - Array of recipient objects
+ * @param {RequestCb} callback
+ * @return {Promise}
+ *
+ */
+ update: function(id, recipientList, callback) {
+ var reqOpts;
+
+ if (!id) {
+ return Promise.reject(new Error('recipient list id is required')).asCallback(callback);
}
- var reqOpts = {
- uri: api + '/' + options.id
- };
-
- if (options.num_rcpt_errors) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors;
- delete options.num_rcpt_errors;
+ if (!recipientList || typeof recipientList === 'function') {
+ return Promise.reject(new Error('recipient list is required')).asCallback(callback);
}
- reqOpts.json = toApiFormat(options);
+ reqOpts = {
+ uri: api + '/' + id,
+ json: recipientList,
+ qs: {
+ num_rcpt_errors: recipientList.num_rcpt_errors
+ }
+ };
- client.put(reqOpts, callback);
- }
- };
+ return client.put(reqOpts).asCallback(callback);
+ },
- recipientLists['delete'] = function(id, callback) {
- if (typeof id === 'function') {
- callback = id;
- id = null;
- }
+ /**
+ * Delete an existing recipient list
+ * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-delete-delete
+ *
+ * @param {string} id - ID of the list to be updated
+ * @param {RequestCb} callback
+ * @return {Promise}
+ *
+ */
+ delete: function(id, callback) {
+ var reqOpts;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
+ }
- if (!id) {
- callback(new Error('id is required'));
- return;
- }
+ reqOpts = {
+ uri: api + '/' + id
+ };
- var reqOpts = {
- uri: api + '/' + id
- };
- client['delete'](reqOpts, callback);
+ return client.delete(reqOpts).asCallback(callback);
+ }
};
- return recipientLists;
};
diff --git a/lib/relayWebhooks.js b/lib/relayWebhooks.js
index dc22bce..033fef9 100644
--- a/lib/relayWebhooks.js
+++ b/lib/relayWebhooks.js
@@ -1,114 +1,106 @@
'use strict';
-var api = 'relay-webhooks';
-
-var toApiFormat = function(input) {
- var model = {
- match: {}
- };
-
- model.target = input.target;
- model.match.domain = input.domain;
-
- model.name = input.name;
- model.auth_token = input.authToken;
- model.match.protocol = input.protocol;
-
- return model;
-};
+const Promise = require('./Promise');
+const api = 'relay-webhooks';
module.exports = function(client) {
- var relayWebhooks = {
- all: function(callback) {
- var reqOpts = {
+ return {
+ /**
+ * List all relay webhooks
+ *
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ list: function(callback) {
+ let reqOpts = {
uri: api
};
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- find: function(relayWebhookId, callback) {
- if(typeof relayWebhookId === 'function') {
- callback = relayWebhookId;
- relayWebhookId = null;
- }
-
- if(!relayWebhookId) {
- callback(new Error('relayWebhookId is required'));
- return;
+ /**
+ * Get details about a specified relay webhook by its id
+ *
+ * @param {string} id - the id of the relay webhook you want to look up
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ get: function(id, callback) {
+ let options;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- var options = {
- uri: api + '/' + relayWebhookId
+ options = {
+ uri: api + '/' + id
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- create: function(options, callback) {
- if(typeof options === 'function') {
- callback = options;
- options = null;
- }
-
- if(!options) {
- callback(new Error('options are required'));
- return;
+ /**
+ * Create a new relay webhook
+ *
+ * @param {Object} webhook - an object of [relay webhook attributes]{https://developers.sparkpost.com/api/relay-webhooks#header-relay-webhooks-object-properties}
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ create: function(webhook, callback) {
+ let reqOpts;
+
+ if (!webhook || typeof webhook !== 'object') {
+ return Promise.reject(new Error('webhook object is required')).asCallback(callback);
}
- if(!options.target) {
- callback(new Error('target is required in options'));
- return;
- }
-
- if(!options.domain) {
- callback(new Error('domain is required in options'));
- return;
- }
-
- var reqOpts = {
+ reqOpts = {
uri: api
- , json: toApiFormat(options)
+ , json: webhook
};
- client.post(reqOpts, callback);
+ return client.post(reqOpts).asCallback(callback);
},
- update: function(options, callback) {
- if(typeof options === 'function') {
- callback = options;
- options = null;
- }
-
- if(!options) {
- callback(new Error('options are required'));
- return;
+ /**
+ * Update an existing relay webhook
+ *
+ * @param {string} id - the id of the relay webhook you want to update
+ * @param {Object} webhook - an object of [relay webhook attributes]{https://developers.sparkpost.com/api/relay-webhooks#header-relay-webhooks-object-properties}
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ update: function(id, webhook, callback) {
+ let reqOpts;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- if(!options.relayWebhookId) {
- callback(new Error('relayWebhookId is required in options'));
- return;
+ if (!webhook || typeof webhook !== 'object') {
+ return Promise.reject(new Error('webhook object is required')).asCallback(callback);
}
- var relayWebhookId = options.relayWebhookId;
- var reqOpts = {
- uri: api + '/' + relayWebhookId
- , json: toApiFormat(options)
+ reqOpts = {
+ uri: api + '/' + id
+ , json: webhook
};
- client.put(reqOpts, callback);
- },
- delete: function(relayWebhookId, callback) {
- if (typeof relayWebhookId === 'function') {
- callback = relayWebhookId;
- relayWebhookId = null;
- }
- if (!relayWebhookId) {
- callback(new Error('relayWebhookId is required'));
- return;
+ return client.put(reqOpts).asCallback(callback);
+ },
+ /**
+ * Delete an existing relay webhook
+ *
+ * @param {string} id - the id of the relay webhook you want to delete
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ delete: function(id, callback) {
+ let options;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- var options = {
- uri: api + '/' + relayWebhookId
+ options = {
+ uri: api + '/' + id
};
- client.delete(options, callback);
+ return client.delete(options, callback).asCallback(callback);
}
};
-
- return relayWebhooks;
};
diff --git a/lib/sendingDomains.js b/lib/sendingDomains.js
index b85e357..faf3c70 100644
--- a/lib/sendingDomains.js
+++ b/lib/sendingDomains.js
@@ -1,122 +1,142 @@
'use strict';
-var api = 'sending-domains'
- , toApiFormat = require('./toApiFormat');
-
-/*
- * "Class" declaration, Sending Domains API exposes five functions:
- * - create: creates a new sending domain
- * - update: updates an existing sending domain
- * - delete: deletes an existing sending domain
- * - verify: validates specified verification field types on a sending domain
- * - all: retreives a list of sending domains
- * - find: retreives info about a specific sending domain
- */
-module.exports = function (client) {
-
- var sendingDomains = {
- all: function (callback) { //list
- var options = {
+const Promise = require('./Promise');
+const api = 'sending-domains';
+
+module.exports = function(client) {
+
+ return {
+ /**
+ * Lists all sending domains
+ *
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ list: function(callback) {
+ let options = {
uri: api
};
- client.get(options, callback);
+
+ return client.get(options).asCallback(callback);
},
- find: function (domain, callback) { //retrieve
- if(typeof domain === 'function') {
- callback = domain;
- domain = null;
- }
- if(!domain) {
- callback(new Error('domain is required'));
- return;
+ /**
+ * Get a single sending domain, by domain
+ *
+ * @param {string} domain - The domain name to get
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ get: function(domain, callback) {
+ let options;
+
+ if (!domain || typeof domain === 'function') {
+ return Promise.reject(new Error('domain is required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api + '/' + domain
};
- client.get(options, callback);
- },
- create: function (domainBody, callback) {
- if(typeof domainBody === 'function') {
- callback = domainBody;
- domainBody = null;
- }
- if(!domainBody) {
- callback(new Error('domainBody is required'));
- return;
- }
+ return client.get(options).asCallback(callback);
+ },
- if(!domainBody.domain) {
- callback(new Error('domain is required in the domainBody'));
- return;
+ /**
+ * Creates a new sending domain
+ *
+ * @param {Object} createOpts - attributes used to create the new domain
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ create: function(createOpts, callback) {
+ let options;
+
+ if (!createOpts || typeof createOpts !== 'object') {
+ return Promise.reject(new Error('create options are required')).asCallback(callback);
}
- var options = {
- uri: api
- , json: toApiFormat(domainBody)
+ options = {
+ uri: api,
+ json: createOpts
};
- client.post(options, callback);
+
+ return client.post(options).asCallback(callback);
},
- update: function (domainBody, callback) {
- if(typeof domainBody === 'function') {
- callback = domainBody;
- domainBody = null;
- }
- if(!domainBody) {
- callback(new Error('domainBody is required'));
- return;
+ /**
+ * Update an existing sending domain
+ *
+ * @param {string} domain - The domain to update
+ * @param {Object} updateOpts - Hash of the sending domain attributes to update
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ update: function(domain, updateOpts, callback) {
+ let options;
+
+ if (typeof domain !== 'string') {
+ return Promise.reject(new Error('domain is required')).asCallback(callback);
}
- if(!domainBody.domain) {
- callback(new Error('domain is required in the domainBody'));
- return;
+ if (!updateOpts || typeof updateOpts !== 'object') {
+ return Promise.reject(new Error('update options are required')).asCallback(callback);
}
- var obj = toApiFormat(domainBody);
- var options = {
- uri: api + '/' + obj.domain
- , json: toApiFormat(domainBody)
+ options = {
+ uri: api + '/' + domain,
+ json: updateOpts
};
- client.put(options, callback);
+
+ return client.put(options).asCallback(callback);
},
+
+ /**
+ * Delete an existing sending domain
+ *
+ * @param {string} domain - The domain to delete
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
delete: function(domain, callback) {
- if (typeof domain === 'function') {
- callback = domain;
- domain = null;
- }
+ let options;
- if (!domain) {
- callback(new Error('domain is required'));
- return;
+ if (typeof domain !== 'string') {
+ return Promise.reject(new Error('domain is required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api + '/' + domain
};
- client.delete(options, callback);
+
+ return client.delete(options).asCallback(callback);
},
- verify: function (options, callback) {
- options = options || {};
- if(!options.domain) {
- callback(new Error('domain is required'));
- return;
+ /**
+ * Verify an existing sending domain
+ *
+ * @param {string} domain - The domain to verify
+ * @param {Object} options - Hash of options to include in verification request
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ verify: function(domain, options, callback) {
+ let reqOpts;
+
+ if (typeof domain !== 'string') {
+ return Promise.reject(new Error('domain is required')).asCallback(callback);
+ }
+
+ if (!options || typeof options !== 'object') {
+ return Promise.reject(new Error('verification options are required')).asCallback(callback);
}
- var reqOpts = {
- uri: api + '/' + options.domain + '/verify',
- json: {
- dkim_verify: options.verifyDKIM !== false,
- spf_verify: options.verifySPF !== false
- }
+ reqOpts = {
+ uri: api + '/' + domain + '/verify',
+ json: options
};
- client.post(reqOpts, callback);
+ return client.post(reqOpts).asCallback(callback);
}
};
- return sendingDomains;
};
diff --git a/lib/sparkpost.js b/lib/sparkpost.js
index 3f59e1a..67f1b2c 100644
--- a/lib/sparkpost.js
+++ b/lib/sparkpost.js
@@ -1,24 +1,27 @@
'use strict';
-var version = require( '../package.json').version
+var version = require('../package.json').version
, url = require('url')
- , request = require( 'request')
- , _ = require( 'lodash' );
+ , Promise = require('./Promise')
+ , request = require('request')
+ , _ = require('lodash')
+ , defaults, resolveUri, handleOptions, createSparkPostError, SparkPost;
//REST API Config Defaults
-var defaults = {
+defaults = {
origin: 'https://api.sparkpost.com:443',
- apiVersion: 'v1'
+ apiVersion: 'v1',
+ debug: false
};
-var resolveUri = function(origin, uri) {
- if(!/^http/.test(uri)) {
+resolveUri = function(origin, uri) {
+ if (!/^http/.test(uri)) {
uri = url.resolve(origin, uri);
}
return uri;
};
-var handleOptions = function(apiKey, options) {
+handleOptions = function(apiKey, options) {
if (typeof apiKey === 'object') {
options = apiKey;
options.key = process.env.SPARKPOST_API_KEY;
@@ -32,13 +35,23 @@ var handleOptions = function(apiKey, options) {
return options;
};
-var SparkPost = function(apiKey, options) {
+createSparkPostError = function(res, body) {
+ var err = new Error(res.statusMessage);
+ body = body || {};
+ err.name = 'SparkPostError';
+ err.errors = body.errors;
+ err.statusCode = res.statusCode;
+
+ return err;
+};
+
+SparkPost = function(apiKey, options) {
options = handleOptions(apiKey, options);
this.apiKey = options.key || process.env.SPARKPOST_API_KEY;
- if(typeof this.apiKey === 'undefined') {
+ if (typeof this.apiKey === 'undefined') {
throw new Error('Client requires an API Key.');
}
@@ -54,6 +67,7 @@ var SparkPost = function(apiKey, options) {
//Optional client config
this.origin = options.origin;
this.apiVersion = options.apiVersion || defaults.apiVersion;
+ this.debug = (typeof options.debug === 'boolean') ? options.debug : defaults.debug;
this.inboundDomains = require('./inboundDomains')(this);
this.messageEvents = require('./messageEvents')(this);
@@ -67,17 +81,18 @@ var SparkPost = function(apiKey, options) {
this.webhooks = require('./webhooks')(this);
};
-SparkPost.prototype.request = function( options, callback ) {
+SparkPost.prototype.request = function(options, callback) {
+ var baseUrl;
// we need options
- if(!_.isPlainObject(options)) {
- throw new TypeError( 'options argument is required' );
+ if (!_.isPlainObject(options)) {
+ throw new TypeError('options argument is required');
}
- var baseUrl = this.origin + '/api/' + this.apiVersion + '/';
+ baseUrl = this.origin + '/api/' + this.apiVersion + '/';
// if we don't have a fully qualified URL let's make one
- options.uri = resolveUri( baseUrl, options.uri );
+ options.uri = resolveUri(baseUrl, options.uri);
// merge headers
options.headers = _.merge({}, this.defaultHeaders, options.headers);
@@ -93,47 +108,61 @@ SparkPost.prototype.request = function( options, callback ) {
options.gzip = true;
}
- request(options, function(err, res, body) {
- var invalidCodeRegex = /(5|4)[0-9]{2}/;
- if(err) {
- return callback(err, res);
- } else if(invalidCodeRegex.test(res.statusCode)) {
- body = body || {};
- err = new Error(res.statusMessage);
- err.name = 'SparkPostError';
- err.errors = body.errors;
- err.statusCode = res.statusCode;
- return callback(err, res);
- } else {
- return callback(null, res);
- }
- });
+ // set debug
+ options.debug = (typeof options.debug === 'boolean') ? options.debug : this.debug;
+
+ return new Promise(function(resolve, reject) {
+ request(options, function(err, res, body) {
+ var invalidCodeRegex = /(5|4)[0-9]{2}/
+ , response;
+
+ if (err) {
+ reject(err);
+ } else if (invalidCodeRegex.test(res.statusCode)) {
+ err = createSparkPostError(res, body);
+ reject(err);
+ } else {
+ response = body;
+ if (options.debug) {
+ response.debug = res;
+ }
+ resolve(response);
+ }
+ });
+ }).asCallback(callback);
};
-SparkPost.prototype.get = function( options, callback ) {
+SparkPost.prototype.get = function(options, callback) {
options.method = 'GET';
+ options.json = true;
- this.request(options, callback);
+ return this.request(options).asCallback(callback);
};
-SparkPost.prototype.post = function( options, callback ) {
+SparkPost.prototype.post = function(options, callback) {
options.method = 'POST';
- this.request(options, callback);
+ return this.request(options).asCallback(callback);
};
-SparkPost.prototype.put = function( options, callback ) {
+SparkPost.prototype.put = function(options, callback) {
options.method = 'PUT';
- this.request(options, callback);
+ return this.request(options).asCallback(callback);
};
-SparkPost.prototype['delete'] = function( options, callback ) {
+SparkPost.prototype.delete = function(options, callback) {
options.method = 'DELETE';
- this.request(options, callback);
+ return this.request(options).asCallback(callback);
};
-SparkPost.SendGridCompatibility = require('./SendGridCompatibility');
-
module.exports = SparkPost;
+
+/**
+ * Standard error-first callback for HTTP requests
+
+ * @callback RequestCb
+ * @param {Error} err - Any error that occurred
+ * @param {Object} [data] - API response body (or just the value of `body.results`, if it exists)
+ */
diff --git a/lib/subaccounts.js b/lib/subaccounts.js
index 85de232..f4f9cf5 100644
--- a/lib/subaccounts.js
+++ b/lib/subaccounts.js
@@ -1,115 +1,86 @@
'use strict';
-var api = 'subaccounts';
-
-var toApiFormat = function(input) {
- var model = {};
-
- model.name = input.name;
- model.key_label = input.keyLabel;
- model.ip_pool = input.ipPool;
- model.status = input.status;
-
- model.key_grants = Array.isArray(input.keyGrants) ? input.keyGrants : [input.keyGrants];
-
- // server returns 500 if key_valid_ips is empty array
- if (input.keyValidIps) {
- var keyValidIpsIsArray = Array.isArray(input.keyValidIps);
- if (keyValidIpsIsArray && input.keyValidIps.length > 0) {
- model.key_valid_ips = input.keyValidIps;
- } else if (!keyValidIpsIsArray) {
- model.key_valid_ips = [input.keyValidIps];
- }
- }
-
- return model;
-};
-
-var validateCreateOptions = function(input) {
- if (!input.name) {
- return 'name is required';
- }
-
- if (!input.keyLabel) {
- return 'keyLabel is required';
- }
-
- if (!input.keyGrants) {
- return 'keyGrants is required';
- }
-
- return null;
-};
+const Promise = require('./Promise');
+const api = 'subaccounts';
module.exports = function(client) {
var subaccounts = {
- all: function(callback) {
- var options = {
+ /**
+ * List a summary of all subaccounts
+ *
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ list: function(callback) {
+ let options = {
uri: api
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- find: function(subaccountId, callback) {
- if(typeof subaccountId === 'function') {
- callback = subaccountId;
- subaccountId = null;
- }
-
- if (!subaccountId) {
- callback(new Error('subaccountId is required'));
- return;
+ /**
+ * Get details about a specified subaccount by its id
+ *
+ * @param {string} id - the id of the subaccount you want to look up
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ get: function(id, callback) {
+ var options;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- var options = {
- uri: api + '/' + subaccountId
+ options = {
+ uri: api + '/' + id
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- create: function(options, callback) {
- if(typeof options === 'function') {
- callback = options;
- options = null;
- }
-
- if (!options) {
- callback(new Error('options are required'));
- return;
+ /**
+ * Create a new subaccount
+ *
+ * @param subaccount - an object of [subaccount attributes]{https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes}
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ create: function(subaccount, callback) {
+ var reqOpts;
+
+ if (!subaccount || typeof subaccount !== 'object') {
+ return Promise.reject(new Error('subaccount object is required')).asCallback(callback);
}
- var validation = validateCreateOptions(options);
- if (validation) {
- callback(new Error(validation + ' in options'));
- return;
- }
-
- var reqOpts = {
+ reqOpts = {
uri: api,
- json: toApiFormat(options)
+ json: subaccount
};
- client.post(reqOpts, callback);
+ return client.post(reqOpts).asCallback(callback);
},
- update: function(options, callback) {
- if(typeof options === 'function') {
- callback = options;
- options = null;
+ /**
+ * Update existing subaccount by id
+ *
+ * @param {string} id - the id of the subaccount you want to update
+ * @param {Object} subaccount - an object of [subaccount attributes]{https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1}
+ * @param {RequestCb} callback
+ * @returns {Promise}
+ */
+ update: function(id, subaccount, callback) {
+ var reqOpts;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- if(!options) {
- callback(new Error('options are required'));
- return;
+ if (!subaccount || typeof subaccount !== 'object') {
+ return Promise.reject(new Error('subaccount object is required')).asCallback(callback);
}
- if(!options.subaccountId) {
- callback(new Error('subaccountId is required in options'));
- return;
- }
-
- var subaccountId = options.subaccountId;
- var reqOpts = {
- uri: api + '/' + subaccountId,
- json: toApiFormat(options)
+ reqOpts = {
+ uri: api + '/' + id,
+ json: subaccount
};
- client.put(reqOpts, callback);
+
+ return client.put(reqOpts).asCallback(callback);
}
};
diff --git a/lib/suppressionList.js b/lib/suppressionList.js
index aa130a9..7d4f985 100644
--- a/lib/suppressionList.js
+++ b/lib/suppressionList.js
@@ -1,74 +1,92 @@
'use strict';
-var api = 'suppression-list'
- , toApiFormat = require('./toApiFormat');
+const Promise = require('./Promise');
+const api = 'suppression-list';
module.exports = function(client) {
return {
- search: function(parameters, callback) {
- var options = {
+ /**
+ * Lists all entries in your suppression list,
+ * filtered by an optional set of parameters
+ *
+ * @param {Object} [parameters] - Hash of parameters to filter results
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ list: function(parameters, callback) {
+ let options = {
uri: api
, qs: parameters
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- checkStatus: function(email, callback) {
- if(typeof email === 'function') {
- callback = email;
- email = null;
- }
- if(!email) {
- callback(new Error('email is required'));
- return;
+ /**
+ * Gets a single entry by email address ID
+ *
+ * @param {String} email
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ get: function(email, callback) {
+ let options;
+
+ if (!email || typeof email === 'function') {
+ return Promise.reject(new Error('email is required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api + '/' + email
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- removeStatus: function(email, callback) {
- if(typeof email === 'function') {
- callback = email;
- email = null;
+
+ /**
+ * Updates existing entries, or creates entries
+ * if they don't exist for that email address ID
+ *
+ * @param {Array|Object} listEntries - List of suppression entry objects to upsert
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ upsert: function(listEntries, callback) {
+ let options;
+
+ if (!listEntries || typeof listEntries === 'function') {
+ return Promise.reject(new Error('list entries is required')).asCallback(callback);
}
- if(!email) {
- callback(new Error('email is required'));
- return;
+ if (!Array.isArray(listEntries)) {
+ listEntries = [listEntries];
}
- var options = {
- uri: api + '/' + email
+ options = {
+ uri: api,
+ json: { recipients: listEntries }
};
- client['delete'](options, callback);
- },
- upsert: function(recipients, callback) {
- var options;
- if(typeof recipients === 'function') {
- callback = recipients;
- recipients = null;
- }
+ return client.put(options, callback).asCallback(callback);
+ },
- if(!recipients) {
- callback(new Error('recipient is required'));
- return;
- }
+ /**
+ * Deletes a single entry, by email address ID
+ *
+ * @param {String} email
+ * @param {RequestCb} [callback]
+ * @return {Promise}
+ */
+ delete: function(email, callback) {
+ let options;
- if(!Array.isArray(recipients)) {
- recipients = [recipients];
+ if (!email || typeof email === 'function') {
+ return Promise.reject(new Error('email is required')).asCallback(callback);
}
- recipients = toApiFormat(recipients);
options = {
- uri: api,
- json: { recipients: recipients }
+ uri: api + '/' + email
};
-
- client.put(options, callback);
+ return client.delete(options).asCallback(callback);
}
};
diff --git a/lib/templates.js b/lib/templates.js
index b80dbe3..3e879dd 100644
--- a/lib/templates.js
+++ b/lib/templates.js
@@ -1,111 +1,154 @@
'use strict';
-var api = 'templates'
- , toApiFormat = require('./toApiFormat');
+const api = 'templates';
+const Promise = require('./Promise');
+const _ = require('lodash');
module.exports = function(client) {
- var templates = {
- all: function(callback) {
+ return {
+ /**
+ * List an overview of all templates.
+ *
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ list: function(callback) {
var options = {
uri: api
};
- client.get(options, callback);
+ return client.get(options).asCallback(callback);
},
- find: function(options, callback) {
+ /**
+ * Get details about a specified template by its id.
+ *
+ * @param {string} id
+ * @param {Object} options
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ get: function(id, options, callback) {
+ var reqOpts;
options = options || {};
- if(!options.id) {
- callback(new Error('template id is required'));
- return;
+ if (!id) {
+ return Promise.reject(new Error('template id is required')).asCallback(callback);
}
- var reqOpts = {
- uri: api + '/' + options.id
+ reqOpts = {
+ uri: api + '/' + id
+ , qs: options
};
- if(options.draft) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.draft = options.draft;
- }
-
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- create: function(options, callback) {
- options = options || {};
-
- if (!options.template) {
- callback(new Error('template object is required'));
- return;
+ /**
+ * Create a new template.
+ *
+ * @param {Object} template
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ create: function(template, callback) {
+ var reqOpts;
+
+ if (!template || typeof template !== 'object') {
+ return Promise.reject(new Error('template object is required')).asCallback(callback);
}
- var reqOpts = {
+ reqOpts = {
uri: api
- , json: toApiFormat(options.template)
+ , json: template
};
- client.post(reqOpts, callback);
+ return client.post(reqOpts).asCallback(callback);
},
- update: function(options, callback) {
- options = options || {};
+ /**
+ * Update an existing template.
+ *
+ * @param {String} id
+ * @param {Object} template
+ * @param {Object} options
+ * @param {RequestCb} callback
+ * @returns {Promise}
+ */
+ update: function(id, template, options, callback) {
+ var reqOpts;
+
+ // Handle optional options argument
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
+ }
- if(!options.template) {
- callback(new Error('template object is required'));
- return;
+ if (!id) {
+ return Promise.reject(new Error('template id is required')).asCallback(callback);
}
- var object = toApiFormat(options.template)
- , reqOpts = {
- uri: api + '/' + object.id
- , json: object
- };
+ if (!template || typeof template !== 'object') {
+ return Promise.reject(new Error('template object is required')).asCallback(callback);
+ }
- if(options.update_published) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.update_published = options.update_published;
+ reqOpts = {
+ uri: api + '/' + id
+ , json: template
+ , qs: options
+ };
+
+ return client.put(reqOpts).asCallback(callback);
+ },
+ /**
+ * Delete an existing template.
+ *
+ * @param {String} id
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ delete: function(id, callback) {
+ var options;
+
+ if (!id || typeof id !== 'string') {
+ return Promise.reject(new Error('template id is required')).asCallback(callback);
}
- client.put(reqOpts, callback);
+ options = {
+ uri: api + '/' + id
+ };
+ return client.delete(options).asCallback(callback);
},
- preview: function(options, callback) {
+ /**
+ * Preview the most recent version of an existing template by id.
+ *
+ * @param {String} id
+ * @param {Object} options
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ preview: function(id, options, callback) {
+ var reqOpts;
options = options || {};
- if(!options.id) {
- callback(new Error('template id is required'));
- return;
+ // Handle optional options argument
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
}
- var reqOpts = {
- uri: api + '/' + options.id + '/preview'
- , json: {
- substitution_data: options.data
- }
- };
-
- if (options.draft) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.draft = options.draft;
+ if (!id) {
+ return Promise.reject(new Error('template id is required')).asCallback(callback);
}
- client.post(reqOpts, callback);
- }
- };
+ reqOpts = {
+ uri: api + '/' + id + '/preview'
+ , json: _.cloneDeep(options)
+ , qs: {}
+ };
- templates['delete'] = function(id, callback) {
- if (typeof id === 'function') {
- callback = id;
- id = null;
- }
+ if (reqOpts.json.draft) {
+ reqOpts.qs.draft = reqOpts.json.draft;
+ delete reqOpts.json.draft;
+ }
- if (!id) {
- callback(new Error('template id is required'));
- return;
+ return client.post(reqOpts).asCallback(callback);
}
-
- var options = {
- uri: api + '/' + id
- };
- client['delete'](options, callback);
};
-
- return templates;
};
diff --git a/lib/toApiFormat.js b/lib/toApiFormat.js
deleted file mode 100644
index 3f33a46..0000000
--- a/lib/toApiFormat.js
+++ /dev/null
@@ -1,52 +0,0 @@
-'use strict';
-var _ = require('lodash')
- , pointer = require('json-pointer');
-
-var excludeList = [
- '/substitution_data',
- '/tags',
- '/metadata',
- '/attributes',
- '/headers',
- '/content/email_rfc822'
-];
-
-function snakedKeyClone(source) {
- if (!_.isObject(source)) {
- return source;
- }
-
- var target = Array.isArray(source) ? [] : {};
-
- Object.keys(source).forEach(function(key) {
- target[_.snakeCase(key)] = snakedKeyClone(source[key]);
- });
-
- return target;
-}
-
-module.exports = function toApiFormat(source) {
-
- var excludedObjects = {};
-
- // Look in the source object for the excluded pointers and take a copy of the
- // objects pointed to by those keys. Then remove them from the source object.
- excludeList.forEach(function(exclusionPointer) {
- if (pointer.has(source, exclusionPointer)) {
- pointer.set(excludedObjects, exclusionPointer, pointer.get(source, exclusionPointer));
- pointer.remove(source, exclusionPointer);
- }
- });
-
- // Make a clone of the remaining source object but with snaked case keys
- var target = snakedKeyClone(source);
-
- // Reinstated the un-modified objects into the target
- excludeList.forEach(function(exclusionPointer) {
- if (pointer.has(excludedObjects, exclusionPointer)) {
- pointer.set(target, exclusionPointer, pointer.get(excludedObjects, exclusionPointer));
- }
- });
-
- return target;
-};
diff --git a/lib/transmissions.js b/lib/transmissions.js
index b7317ec..0625780 100644
--- a/lib/transmissions.js
+++ b/lib/transmissions.js
@@ -1,7 +1,7 @@
'use strict';
-var api = 'transmissions'
- , toApiFormat = require('./toApiFormat');
+const api = 'transmissions';
+const Promise = require('./Promise');
/*
* "Class" declaration, Transmissions exposes three functions, one for sending a transmission,
@@ -11,66 +11,77 @@ var api = 'transmissions'
module.exports = function(client) {
return {
- send: function (options, callback) {
- options = options || {};
-
- if(!options.transmissionBody) {
- callback(new Error('transmissionBody is required'));
- return;
+ /**
+ * List an overview of all transmissions in the account
+ *
+ * @param {Object} options
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ list: function(options, callback) {
+ var reqOpts;
+
+ // Handle optional options argument
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
}
- var mappedInput = toApiFormat(options.transmissionBody);
-
- var reqOpts = {
+ reqOpts = {
uri: api,
- json: mappedInput
+ qs: options
};
- if (options.num_rcpt_errors) {
- reqOpts.qs = reqOpts.qs || {};
- reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors;
- delete options.num_rcpt_errors;
- }
-
- client.post(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- all: function (options, callback) {
- if(typeof options === 'function') {
- callback = options;
- options = {};
+ /**
+ * Retrieve the details about a transmission by its id
+ *
+ * @param {String} id
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ get: function(id, callback) {
+ var options;
+
+ if (typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- var reqOpts = {
- uri: api,
- qs: {}
+ options = {
+ uri: api + '/' + id
};
- if (options.campaign_id) {
- reqOpts.qs.campaign_id = options.campaign_id;
+ return client.get(options).asCallback(callback);
+ },
+ /**
+ * Sends a message by creating a new transmission
+ *
+ * @param {Object} transmission
+ * @param {Object} options
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ send: function(transmission, options, callback) {
+ var reqOpts;
+
+ if (!transmission || typeof transmission !== 'object') {
+ return Promise.reject(new Error('transmission object is required')).asCallback(callback);
}
- if (options.template_id) {
- reqOpts.qs.template_id = options.template_id;
+ // Handle optional options argument
+ if (typeof options === 'function') {
+ callback = options;
+ options = {};
}
- client.get(reqOpts, callback);
- },
- find: function (transmissionID, callback) {
- var options = {
- uri: api + '/' + transmissionID
+ reqOpts = {
+ uri: api,
+ json: transmission,
+ qs: options
};
- if(typeof transmissionID === 'function') {
- callback = transmissionID;
- transmissionID = null;
- }
-
- if(!transmissionID) {
- callback(new Error('transmissionID is required'));
- return;
- }
-
- client.get(options, callback);
+ return client.post(reqOpts).asCallback(callback);
}
};
diff --git a/lib/webhooks.js b/lib/webhooks.js
index c590ed8..76dd824 100644
--- a/lib/webhooks.js
+++ b/lib/webhooks.js
@@ -1,173 +1,241 @@
'use strict';
-var api = 'webhooks'
- , toApiFormat = require('./toApiFormat');
+const Promise = require('./Promise');
+const api = 'webhooks';
module.exports = function(client) {
- var webhooks = {
- all: function (options, callback) {
+ return {
+
+ /**
+ * Lists all webhooks
+ *
+ * @param {Object} [options] - Hash of options
+ * @param {string} [options.timezone] - The timezone to use for the last_successful and last_failure properties.
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ list: function(options, callback) {
var reqOpts = {
- uri: api
+ uri: api,
+ qs: {}
};
- if (typeof options === 'function') {
+ if (!options || typeof options === 'function') {
callback = options;
options = {};
}
if (options.timezone) {
- reqOpts.qs = reqOpts.qs || {};
reqOpts.qs.timezone = options.timezone;
}
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- describe: function (options, callback) {
- options = options || {};
- if (!options.id) {
- callback(new Error('id is required'));
- return;
+ /**
+ * Get a single webhook by ID
+ *
+ * @param {string} id - The ID of the webhook to get
+ * @param {Object} [options] - Hash of options
+ * @param {string} [options.timezone] - The timezone to use for the last_successful and last_failure properties.
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ get: function(id, options, callback) {
+ var reqOpts;
+
+ if (!options || typeof options === 'function') {
+ callback = options;
+ options = {};
}
- var reqOpts = {
- uri: api + '/' + options.id
+
+ if (typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
+ }
+
+ reqOpts = {
+ uri: api + '/' + id,
+ qs: {}
};
if (options.timezone) {
- reqOpts.qs = reqOpts.qs || {};
reqOpts.qs.timezone = options.timezone;
}
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- create: function (webhook, callback) {
- if (typeof webhook === 'function') {
- callback = webhook;
- webhook = null;
- }
- if (!webhook) {
- callback(new Error('webhook object is required'));
- return;
+ /**
+ * Creates a new webhook
+ *
+ * @param {Object} webhook - attributes used to create the new webhook
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ create: function(webhook, callback) {
+ var options;
+
+ if (!webhook || typeof webhook === 'function') {
+ return Promise.reject(new Error('webhook object is required')).asCallback(callback);
}
- var options = {
- uri: api
- , json: toApiFormat(webhook)
+
+ options = {
+ uri: api,
+ json: webhook
};
- client.post(options, callback);
+ return client.post(options).asCallback(callback);
},
- update: function (webhook, callback) {
- var object, options, id;
-
- if (typeof webhook === 'function') {
- callback = webhook;
- webhook = null;
- }
- if (!webhook) {
- callback(new Error('webhook object is required'));
- return;
+ /**
+ * Update an existing webhook
+ *
+ * @param {string} id - The ID of the webhook to update
+ * @param {Object} webhook - Hash of the webhook attributes to update
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ update: function(id, webhook, callback) {
+ var options;
+ if (!id) {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- if (!webhook.id) {
- callback(new Error('webhook.id is required'));
- return;
+ if (!webhook || typeof webhook === 'function') {
+ return Promise.reject(new Error('webhook object is required')).asCallback(callback);
}
- id = webhook.id;
- delete webhook.id;
-
- object = toApiFormat(webhook);
options = {
- uri: api + '/' + id
- , json: object
+ uri: api + '/' + id,
+ json: webhook
};
- client.put(options, callback);
+ delete options.json.id;
+
+ return client.put(options).asCallback(callback);
},
- delete: function (id, callback) {
- if (typeof id === 'function') {
- callback = id;
- id = null;
- }
- if (!id) {
- callback(new Error('id is required'));
- return;
+ /**
+ * Delete an existing webhook
+ *
+ * @param {string} id - The ID of the webhook to delete
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ delete: function(id, callback) {
+ var options;
+
+ if (!id || typeof id === 'function') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- var options = {
+ options = {
uri: api + '/' + id
};
- client.delete(options, callback);
+ return client.delete(options).asCallback(callback);
},
- validate: function(options, callback) {
- options = options || {};
- if(!options.id) {
- callback(new Error('id is required'));
- return;
+ /**
+ * Sends an example message event batch from the Webhook API to the target URL.
+ *
+ * @param {string} id - The ID of the webhook to validate
+ * @param {Object} options - Hash of options used to validate the webhook
+ * @param {string} options.message - The message (payload) to send to the webhook consumer.
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ validate: function(id, options, callback) {
+ var reqOpts;
+
+ if (typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
}
- if(!options.message) {
- callback(new Error('message is required'));
- return;
+ if (!options || typeof options === 'function' || !options.message) {
+ return Promise.reject(new Error('message is required')).asCallback(callback);
}
- var reqOpts = {
- uri: api + '/' + options.id + '/validate'
- , json: {
+ reqOpts = {
+ uri: api + '/' + id + '/validate',
+ json: {
message: options.message
}
};
- client.post(reqOpts, callback);
+ return client.post(reqOpts).asCallback(callback);
},
- getBatchStatus: function(options, callback) {
- options = options || {};
- if(!options.id) {
- callback(new Error('id is required'));
- return;
+ /**
+ * Gets recent status information about a webhook.
+ *
+ * @param {string} id - The ID of the webhook to check
+ * @param {Object} [options] - Hash of options
+ * @param {string} [options.limit] - The maximum number of results to return.
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ getBatchStatus: function(id, options, callback) {
+ var reqOpts;
+
+ if (!options || typeof options === 'function') {
+ callback = options;
+ options = {};
}
- var reqOpts = {
- uri: api + '/' + options.id + '/batch-status'
+ if (typeof id !== 'string') {
+ return Promise.reject(new Error('id is required')).asCallback(callback);
+ }
+
+ reqOpts = {
+ uri: api + '/' + id + '/batch-status',
+ qs: {}
};
if (options.limit) {
- reqOpts.qs = reqOpts.qs || {};
reqOpts.qs.limit = options.limit;
}
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
+
+ /**
+ * Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL.
+ *
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
getDocumentation: function(callback) {
var reqOpts = {
uri: api + '/events/documentation'
};
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
},
- getSamples: function(options, callback){
+
+ /**
+ * Lists examples of the event data that will be posted to a webhook consumer.
+ *
+ * @param {Object} [options] - Hash of options
+ * @param {string} [options.events] - A comma delimited list of events to get samples of.
+ * @param {RequestCb} [callback]
+ * @returns {Promise}
+ */
+ getSamples: function(options, callback) {
var reqOpts = {
- uri: api + '/events/samples'
+ uri: api + '/events/samples',
+ qs: {}
};
- if (typeof options === 'function') {
+ if (!options || typeof options === 'function') {
callback = options;
options = {};
}
if (options.events) {
- reqOpts.qs = reqOpts.qs || {};
reqOpts.qs.events = options.events;
}
- client.get(reqOpts, callback);
+ return client.get(reqOpts).asCallback(callback);
}
};
-
- return webhooks;
};
diff --git a/package.json b/package.json
index 05f8268..f4bd59e 100644
--- a/package.json
+++ b/package.json
@@ -4,8 +4,10 @@
"description": "A Node.js wrapper for interfacing with your favorite SparkPost APIs",
"main": "./lib/sparkpost.js",
"scripts": {
- "test": "grunt",
- "ci": "grunt && grunt coveralls:grunt_coveralls_coverage"
+ "coveralls": "cat ./test/reports/lcov.info | coveralls",
+ "pretest": "eslint lib/**",
+ "test": "istanbul cover --report lcov --dir test/reports/ _mocha --recursive ./test/spec --grep ./test/**/*.spec.js -- --colors --reporter spec",
+ "postversion": "git push upstream && git push --tags upstream"
},
"keywords": [
"email",
@@ -22,26 +24,20 @@
},
"homepage": "https://github.com/SparkPost/node-sparkpost",
"devDependencies": {
- "chai": "1.9.1",
- "grunt": "0.4.5",
- "grunt-bump": "^0.3.1",
- "grunt-contrib-jshint": "0.10.0",
- "grunt-coveralls": "^1.0.0",
- "grunt-shell": "1.1.1",
- "istanbul": "0.3.2",
- "jshint-stylish": "0.4.0",
- "matchdep": "0.3.0",
- "mocha": "1.21.4",
- "nock": "^7.2.2",
- "proxyquire": "1.0.1",
- "sinon": "^1.14.1",
- "sinon-chai": "2.5.0",
- "time-grunt": "1.0.0",
- "xunit-file": "0.0.5"
+ "chai": "^3.5.0",
+ "chai-as-promised": "^6.0.0",
+ "coveralls": "^2.11.12",
+ "eslint": "^3.3.1",
+ "eslint-config-sparkpost": "^1.2.0",
+ "istanbul": "^0.4.5",
+ "mocha": "^3.0.2",
+ "nock": "^9.0.0",
+ "sinon": "^1.17.5",
+ "sinon-as-promised": "^4.0.2",
+ "sinon-chai": "^2.8.0"
},
"dependencies": {
- "json-pointer": "^0.5.0",
"lodash": "^4.13.1",
- "request": "^2.72.0"
+ "request": "^2.74.0"
}
}
diff --git a/test/spec/SendGridCompatibility/Email.spec.js b/test/spec/SendGridCompatibility/Email.spec.js
deleted file mode 100644
index d995c8e..0000000
--- a/test/spec/SendGridCompatibility/Email.spec.js
+++ /dev/null
@@ -1,154 +0,0 @@
-var chai = require('chai')
- , expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai')
- , email = require('../../../lib/SendGridCompatibility/Email');
-
-chai.use(sinonChai);
-
-describe('SendGrid Email Object', function() {
- var tmpEmail
- , payload = {
- to: ['fake@email.org', 'real@notreally.net'],
- toname: ['Fakey Fakerson', 'Realy Realerson'],
- from: 'a.sender@company.com',
- fromname: 'A. Sender',
- subject: 'Sale',
- text: 'Look at this sale!',
- html: 'Look
at this sale!
',
- bcc: ['bcc@bbc.co.uk', 'bcc@cbc.ca'],
- replyto: 'a.replyto@company.com',
- date: new Date(),
- files: [
- {
- filename: 'name.txt',
- path: '../../../../../../',
- url: 'www.google.com',
- content: '?'
- }
- ],
- file_data: {asdf: 'asdf'},
- headers: {asdfasdf: 'asdfasdf'}
- };
-
- describe('instantiation', function() {
- it('should handle empty input', function() {
- tmpEmail = new email();
- expect(Object.keys(tmpEmail).length).to.equal(0);
- });
- it('should handle a payload', function() {
- tmpEmail = new email(payload);
- for (var index in tmpEmail) {
- if(typeof tmpEmail[index] !== 'function'){
- expect(tmpEmail[index]).to.deep.equal(payload[index]);
- }
- }
- });
- });
-
- describe('compatibility functions: ', function() {
- beforeEach(function() {
- tmpEmail = new email(payload);
- });
- it('addTo', function() {
- tmpEmail.to = undefined;
- tmpEmail.addTo('fake@email.org');
- tmpEmail.addTo('real@notreally.net');
- tmpEmail.addTo('asdf@asdf.com');
- expect(tmpEmail.to).to.deep.equal(['fake@email.org','real@notreally.net','asdf@asdf.com']);
- });
- it('setFrom', function(){
- tmpEmail.setFrom('email@email.edu');
- expect(tmpEmail.from).to.equal('email@email.edu');
- });
- it('setSubject', function(){
- tmpEmail.setSubject('new subject');
- expect(tmpEmail.subject).to.equal('new subject');
- });
- it('setText', function(){
- tmpEmail.setText('new text');
- expect(tmpEmail.text).to.equal('new text');
- });
- it('setHtml', function(){
- tmpEmail.setHtml('new html
');
- expect(tmpEmail.html).to.equal('new html
');
- });
- it('addHeader', function(){
- tmpEmail.headers = undefined;
- tmpEmail.addHeader('abcd', 'efgh');
- tmpEmail.addHeader('1234', '5678');
- expect(tmpEmail.headers).to.deep.equal({abcd: 'efgh', 1234: '5678'});
- });
- it('setHeaders', function(){
- tmpEmail.setHeaders({oldish: 'new'});
- expect(tmpEmail.headers).to.deep.equal({oldish: 'new'});
- });
- it('addSubstitution', function(){
- tmpEmail.addSubstitution('key', 'value');
- tmpEmail.addSubstitution('attributeName', ['attribute1', 'attribute2']);
- expect(tmpEmail.sub).to.deep.equal({key: ['value'], attributeName: ['attribute1', 'attribute2']});
- });
- it('setSubstitutions', function(){
- tmpEmail.setSubstitutions({index: ['element']});
- expect(tmpEmail.sub).to.deep.equal({index: ['element']});
- });
- it('addSection', function(){
- tmpEmail.addSection('key', 'value');
- tmpEmail.addSection('attributeName', 'attribute1');
- expect(tmpEmail.section).to.deep.equal({key: 'value', attributeName: 'attribute1'});
- });
- it('setSections', function(){
- tmpEmail.setSections({index: 'element'});
- expect(tmpEmail.section).to.deep.equal({index: 'element'});
- });
- it('addUniqueArg', function(){
- try {
- tmpEmail.addUniqueArg();
- } catch (err) {
- expect(err).to.deep.equal(new Error('Unique Argument compatibility is not supported.'));
- }
- });
- it('setUniqueArgs', function(){
- try {
- tmpEmail.setUniqueArgs();
- } catch (err) {
- expect(err).to.deep.equal(new Error('Unique Argument compatibility is not supported.'));
- }
- });
- it('addCategory', function(){
- try {
- tmpEmail.addCategory();
- } catch (err) {
- expect(err).to.deep.equal(new Error('Category compatibility is not supported.'));
- }
- });
- it('setCategories', function(){
- try {
- tmpEmail.setCategories();
- } catch (err) {
- expect(err).to.deep.equal(new Error('Category compatibility is not supported.'));
- }
- });
- it('addFilter', function(){
- try {
- tmpEmail.addFilter();
- } catch (err) {
- expect(err).to.deep.equal(new Error('Filter compatibility is not supported.'));
- }
- });
- it('setFilters', function(){
- try {
- tmpEmail.setFilters();
- } catch (err) {
- expect(err).to.deep.equal(new Error('Filter compatibility is not supported.'));
- }
- });
- it('addFile', function(){
- try {
- tmpEmail.addFile();
- } catch (err) {
- expect(err).to.deep.equal(new Error('File compatibility is not supported.'));
- }
- });
- });
-});
diff --git a/test/spec/SendGridCompatibility/index.spec.js b/test/spec/SendGridCompatibility/index.spec.js
deleted file mode 100644
index 52bd367..0000000
--- a/test/spec/SendGridCompatibility/index.spec.js
+++ /dev/null
@@ -1,137 +0,0 @@
-var chai = require('chai')
- , expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai')
- , nock = require('nock')
- , sendGridCompatibility = require('../../../lib/SendGridCompatibility');
-
-chai.use(sinonChai);
-
-describe('SendGrid Compatibility', function() {
- var sendgrid = new sendGridCompatibility('asdf', 'asdf')
- , transmissions = sendgrid.client.transmissions
- , payload = {
- to: ['fake@email.org', 'real@notreally.net'],
- toname: ['Fakey Fakerson', 'Realy Realerson'],
- from: 'a.sender@company.com',
- fromname: 'A. Sender',
- subject: 'Sale',
- text: 'Look at this sale!',
- html: 'Look
at this sale!
',
- bcc: ['bcc@bbc.co.uk', 'bcc@cbc.ca'],
- replyto: 'a.replyto@company.com',
- date: new Date(),
- files: [
- {
- filename: 'name.txt',
- path: '../../../../../../',
- url: 'www.google.com',
- content: '?'
- }
- ],
- file_data: {asdf: 'asdf'},
- headers: {asdfasdf: 'asdfasdf'},
- sub: {password: ['******'], num: ['one', 'two']},
- section: {something: 'something else'}
- },
- translatedPayload = {
- recipients: [
- {
- address: {
- email: 'fake@email.org',
- name: 'Fakey Fakerson'
- }
- },
- {
- address: {
- email: 'real@notreally.net',
- name: 'Realy Realerson'
- }
- }
- ],
- from: 'a.sender@company.com ',
- html: 'Look
at this sale!
',
- text: 'Look at this sale!',
- subject: 'Sale',
- replyTo: 'a.replyto@company.com',
- customHeaders: {asdfasdf: 'asdfasdf'},
- substitutionData: {
- password: [ '******' ],
- num: [ 'one', 'two' ],
- something: 'something else'
- }
- };
-
- describe('Instantiation', function() {
- it('should expose a send function', function() {
- expect(sendgrid.send).to.be.a.function;
- });
-
- it('should handle building an endpoint from options', function() {
- var sendgrid = new sendGridCompatibility('as', 'df', {port: '5000', host: 'test.sparkpost.com', protocol: 'http'});
- expect(sendgrid.client.origin).to.equal('http://test.sparkpost.com:5000');
- });
- });
-
- describe('send Method', function() {
- var sendSpy, scope;
-
- beforeEach(function() {
- sendSpy = sinon.spy(transmissions, 'send');
- scope = nock('https://api.sparkpost.com')
- .post('/api/v1/transmissions')
- .reply(200, { ok: true });
- });
-
- afterEach(function() {
- transmissions.send.restore(); // restoring function
- });
-
- it('should handle an absence of toname', function(done) {
- var toPayload = {to: 'asdf@qwerty.lg.jp'};
- sendgrid.send(toPayload, function() {
- expect(sendSpy.args[0][0].transmissionBody.recipients).to.deep.equal([{ address: { email: 'asdf@qwerty.lg.jp' }}]);
- done();
- });
- });
-
- it('should translate only substitutions into substitutionData appropriately', function(done) {
- var subPayload = { sub: {password: ['******'], num: ['one', 'two']}};
- sendgrid.send(subPayload, function() {
- expect(sendSpy.args[0][0].transmissionBody.substitutionData).to.deep.equal({ password: [ '******' ], num: [ 'one', 'two' ]});
- done();
- });
- });
-
- it('should translate only sections into substitutionData appropriately', function(done) {
- var sectionPayload = { section: {something: 'something else'}};
- sendgrid.send(sectionPayload, function() {
- expect(sendSpy.args[0][0].transmissionBody.substitutionData).to.deep.equal({ something: 'something else'});
- done();
- });
- });
-
- it('should not form substitutionData without substitutions or sections', function(done) {
- var barePayload = {};
- sendgrid.send(barePayload, function() {
- expect(sendSpy.args[0][0].transmissionBody.substitutionData).to.equal(undefined);
- done();
- });
- });
-
- it('should translate a full payload', function(done) {
- sendgrid.send(payload, function() {
- expect(sendSpy.args[0][0].transmissionBody).to.deep.equal(translatedPayload);
- done();
- });
- });
-
- it('should respond when the test succeeds', function(done) {
- sendgrid.send({}, function(err, res) {
- expect(res.body.ok).to.be.true;
- expect(err).to.equal(null);
- done();
- });
- });
- });
-});
diff --git a/test/spec/inboundDomains.spec.js b/test/spec/inboundDomains.spec.js
index b80e111..ce4b3fe 100644
--- a/test/spec/inboundDomains.spec.js
+++ b/test/spec/inboundDomains.spec.js
@@ -1,105 +1,74 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Inbound Domains Library', function() {
- var client, inboundDomains;
+ let client, inboundDomains;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- delete: sinon.stub().yields()
-
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
inboundDomains = require('../../lib/inboundDomains')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- inboundDomains.all(function() {
- expect(client.get.firstCall.args[0]).to.deep.equal({uri:'inbound-domains'});
- done();
- });
+ describe('list Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return inboundDomains.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'inbound-domains'});
+ });
});
});
- describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- inboundDomains.find('test', function() {
- expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'inbound-domains/test'});
- done();
- });
- });
-
- it('should throw an error if domain is null', function(done) {
- inboundDomains.find(null, function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ describe('get Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return inboundDomains.get('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'inbound-domains/test'});
+ });
});
- it('should throw an error if domain is missing', function(done) {
- inboundDomains.find(function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(inboundDomains.get()).to.be.rejectedWith('domain is required');
});
});
describe('create Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- inboundDomains.create("test", function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('inbound-domains');
- done();
- });
+ it('should call client post method with the appropriate uri and payload', function() {
+ let createOpts = {domain: 'test'};
+ return inboundDomains.create(createOpts)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('inbound-domains');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(createOpts);
+ });
});
- it('should throw an error if domain is null', function(done) {
- inboundDomains.create(null, function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if domain is missing', function(done) {
- inboundDomains.create(function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(inboundDomains.create()).to.be.rejectedWith('create options are required');
});
});
describe('delete Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- inboundDomains.delete('test', function(err, data) {
- expect(client.delete.firstCall.args[0].uri).to.equal('inbound-domains/test');
- done();
- });
- });
-
- it('should throw an error if domain is null', function(done) {
- inboundDomains.delete(null, function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should call client delete method with the appropriate uri', function() {
+ return inboundDomains.delete('test')
+ .then(function () {
+ expect(client.delete.firstCall.args[0].uri).to.equal('inbound-domains/test');
+ });
});
- it('should throw an error if domain is missing', function(done) {
- inboundDomains.delete(function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(inboundDomains.delete()).to.be.rejectedWith('domain is required');
});
});
});
diff --git a/test/spec/messageEvents.spec.js b/test/spec/messageEvents.spec.js
index e26aee9..5b9fdfc 100644
--- a/test/spec/messageEvents.spec.js
+++ b/test/spec/messageEvents.spec.js
@@ -1,23 +1,28 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
, sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , Promise = require('../../lib/Promise');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Message Events Library', function() {
- var client, templates;
+ let client, messageEvents;
beforeEach(function() {
client = {
- get: sinon.stub().yields()
+ get: sinon.stub().resolves({})
};
messageEvents = require('../../lib/messageEvents')(client);
});
describe('search Method', function() {
- it('should call client get method with the appropriate parameters', function(done) {
+ it('should call client get method with the appropriate parameters', function() {
var options = {
bounce_classes: '10,50',
campaign_ids: 'test_campaign',
@@ -34,15 +39,15 @@ describe('Message Events Library', function() {
to: '2016-11-14T16:15',
transmission_ids: '65832150921904138'
};
- messageEvents.search(options, function(err, data) {
- Object.keys(options).forEach(function(key) {
- expect(client.get.firstCall.args[0].qs).to.have.property(key).and.equal(options[key]);
+ return messageEvents.search(options)
+ .then(function() {
+ Object.keys(options).forEach(function(key) {
+ expect(client.get.firstCall.args[0].qs).to.have.property(key).and.equal(options[key]);
+ });
});
- done();
- });
});
- it('should accept arrays as parameters where appropriate', function(done) {
+ it('should accept arrays as parameters where appropriate', function() {
var arroptions = {
bounce_classes: [10,50],
campaign_ids: ['campaign1', 'campaignTwo'],
@@ -56,16 +61,16 @@ describe('Message Events Library', function() {
per_page: 5,
timezone: 'America/New_York'
};
- messageEvents.search(arroptions, function(err, data) {
- Object.keys(arroptions).forEach(function(key) {
- var opt = arroptions[key]
- , firstCallQS = client.get.firstCall.args[0].qs;
- if (Array.isArray(opt)) {
- expect(firstCallQS).to.have.property(key).and.equal(opt.toString());
- }
+ return messageEvents.search(arroptions)
+ .then(function() {
+ Object.keys(arroptions).forEach(function(key) {
+ var opt = arroptions[key]
+ , firstCallQS = client.get.firstCall.args[0].qs;
+ if (Array.isArray(opt)) {
+ expect(firstCallQS).to.have.property(key).and.equal(opt.toString());
+ }
+ });
});
- done();
- });
});
});
});
diff --git a/test/spec/recipientLists.spec.js b/test/spec/recipientLists.spec.js
index 670c2be..e0bee3f 100644
--- a/test/spec/recipientLists.spec.js
+++ b/test/spec/recipientLists.spec.js
@@ -1,174 +1,189 @@
-var chai = require('chai')
+'use strict';
+
+var _ = require('lodash')
+ , chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Recipient Lists Library', function() {
var client, recipientLists;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields(),
- 'delete': sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
recipientLists = require('../../lib/recipientLists')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- recipientLists.all(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists');
- done();
- });
+ describe('list', function() {
+
+ it('should call client get method with the appropriate uri', function() {
+ return recipientLists.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists');
+ });
});
+
});
- describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
- recipientLists.find(options, function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists/test');
- done();
- });
+ describe('get', function() {
+
+ it('should call client get method with the appropriate uri', function() {
+ return recipientLists.get('test-id')
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists/test-id');
+ });
});
- it('should throw an error if id is missing', function(done) {
- recipientLists.find(null, function(err) {
- expect(err.message).to.equal('id is required');
- expect(client.get).not.to.have.been.called;
- done();
+ it('should throw an error if id is missing', function() {
+ return expect(recipientLists.get()).to.be.rejectedWith('id is required');
+ });
+
+ it('should not throw an error if optional 2nd argument is a function (callback)', function() {
+ let cb = sinon.stub();
+ return recipientLists.get('test-id', cb).then(() => {
+ expect(cb.callCount).to.equal(1);
});
});
- it('should allow show_recipients to be set in options', function(done) {
+ it('should allow show_recipients to be set in options', function() {
var options = {
- id: 'test',
show_recipients: true
};
- recipientLists.find(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({show_recipients: true});
- done();
- });
+ return recipientLists.get('test-id', options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({show_recipients: true});
+ });
});
+
});
- describe('create Method', function() {
- var test_list = [
- {
- address: {
- email: 'test@test.com',
- name: 'test'
- }
- }
- ];
-
- it('should call client post method with the appropriate uri', function(done) {
- var options = {
- recipients: test_list
+ describe('create', function() {
+
+ it('should call client post method with the appropriate uri and payload', function() {
+ let testList = {
+ id: 'test_list',
+ recipients: [
+ {
+ address: {
+ email: 'test@test.com',
+ name: 'test'
+ }
+ }
+ ]
};
- recipientLists.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('recipient-lists');
- done();
- });
+ return recipientLists.create(testList)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('recipient-lists');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(testList);
+ });
});
- it('should throw an error if id is missing', function(done) {
- recipientLists.create(null, function(err) {
- expect(err.message).to.equal('recipients list is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if no recipients are provided', function() {
+ return Promise.all([
+ expect(recipientLists.create(), 'no recipient list hash at all').to.be.rejectedWith('recipient list is required'),
+ expect(recipientLists.create({}), 'no recipients key').to.be.rejectedWith('recipient list is required'),
+ expect(recipientLists.create(function() {}), 'recipient list is actually a callback').to.be.rejectedWith('recipient list is required')
+ ]);
});
- it('should allow num_rcpt_errors to be set in options', function(done) {
- var options = {
- recipients: test_list,
+ it('should allow num_rcpt_errors to be set in options', function() {
+ var testList = {
+ id: 'test_list',
+ recipients: [
+ {
+ address: {
+ email: 'test@test.com',
+ name: 'test'
+ }
+ }
+ ],
num_rcpt_errors: 3
};
- recipientLists.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3});
- done();
- });
+ return recipientLists.create(testList)
+ .then(function() {
+ expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3});
+ });
});
+
});
- describe('update Method', function() {
- var test_list = [
- {
- address: {
- email: 'test@test.com',
- name: 'test'
- }
- }
- ];
-
- it('should call client put method with the appropriate uri', function(done) {
- var options = {
- id: 'test_list',
- recipients: test_list
+ describe('update', function() {
+
+ it('should call client put method with the appropriate uri and payload', function() {
+ const testList = {
+ recipients: [
+ {
+ address: {
+ email: 'test@test.com',
+ name: 'test'
+ }
+ }
+ ]
};
+ const testId = 'test-id';
- recipientLists.update(options, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('recipient-lists/' + options.id);
- done();
- });
+ return recipientLists.update(testId, testList)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('recipient-lists/' + testId);
+ expect(client.put.firstCall.args[0].json).to.deep.equal(testList);
+ });
});
- it('should throw an error if id is missing', function(done) {
- recipientLists.update(null, function(err) {
- expect(err.message).to.equal('recipients list id is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if recipient list is missing', function() {
+ return expect(recipientLists.update('test-id')).to.be.rejectedWith('recipient list is required');
});
- it('should allow num_rcpt_errors to be set in options', function(done) {
- var options = {
- id: 'test_list',
- recipients: test_list,
+ it('should throw an error if id is missing', function() {
+ return expect(recipientLists.update()).to.be.rejectedWith('recipient list id is required');
+ });
+
+ it('should allow num_rcpt_errors to be set in options', function() {
+ var testList = {
+ recipients: [
+ {
+ address: {
+ email: 'test@test.com',
+ name: 'test'
+ }
+ }
+ ],
num_rcpt_errors: 3
};
- recipientLists.update(options, function(err, data) {
- expect(client.put.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3});
- done();
- });
+ return recipientLists.update('test-id', testList)
+ .then(function() {
+ expect(client.put.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3});
+ });
});
});
- describe('delete Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- recipientLists.delete('test', function(err, data) {
- expect(client['delete'].firstCall.args[0].uri).to.equal('recipient-lists/test');
- done();
- });
- });
+ describe('delete', function() {
- it('should throw an error if id is null', function(done) {
- recipientLists['delete'](null, function(err) {
- expect(err.message).to.equal('id is required');
- expect(client['delete']).not.to.have.been.called;
- done();
- });
+ it('should call client delete method with the appropriate uri', function() {
+ return recipientLists.delete('test')
+ .then(function() {
+ expect(client.delete.firstCall.args[0].uri).to.equal('recipient-lists/test');
+ });
});
- it('should throw an error if id is missing', function(done) {
- recipientLists['delete'](function(err) {
- expect(err.message).to.equal('id is required');
- expect(client['delete']).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(recipientLists.delete()).to.be.rejectedWith('id is required');
});
+
});
+
});
diff --git a/test/spec/relayWebhooks.spec.js b/test/spec/relayWebhooks.spec.js
index ea2991f..35aaa35 100644
--- a/test/spec/relayWebhooks.spec.js
+++ b/test/spec/relayWebhooks.spec.js
@@ -1,163 +1,101 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Relay Webhooks Library', function() {
- var client, relayWebhooks;
+ let client, relayWebhooks;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields(),
- delete: sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
relayWebhooks = require('../../lib/relayWebhooks')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- relayWebhooks.all(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('relay-webhooks');
- done();
- });
+ describe('list Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return relayWebhooks.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('relay-webhooks');
+ });
});
});
- describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- relayWebhooks.find('test', function() {
- expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'relay-webhooks/test'});
- done();
- });
- });
-
- it('should throw an error if relayWebhookId is null', function(done) {
- relayWebhooks.find(null, function(err) {
- expect(err.message).to.equal('relayWebhookId is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ describe('get Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return relayWebhooks.get('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'relay-webhooks/test'});
+ });
});
- it('should throw an error if relayWebhookId is missing', function(done) {
- relayWebhooks.find(function(err) {
- expect(err.message).to.equal('relayWebhookId is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(relayWebhooks.get()).to.be.rejectedWith('id is required');
});
});
describe('create Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- var options = {
+ it('should call client post method with the appropriate uri and payload', function() {
+ let webhook = {
target: 'test',
domain: 'inbound.example.com'
};
- relayWebhooks.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('relay-webhooks');
- done();
- });
- });
-
- it('should throw an error if options is null', function(done) {
- relayWebhooks.create(null, function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if options is missing', function(done) {
- relayWebhooks.create(function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if target is missing from options', function(done) {
- relayWebhooks.create({domain: 'inbound.example.com'}, function(err) {
- expect(err.message).to.equal('target is required in options');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ return relayWebhooks.create(webhook)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('relay-webhooks');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(webhook);
+ });
});
- it('should throw an error if domain is missing from options', function(done) {
- relayWebhooks.create({target: 'test'}, function(err) {
- expect(err.message).to.equal('domain is required in options');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if webhook object is missing', function() {
+ return expect(relayWebhooks.create()).to.be.rejectedWith('webhook object is required');
});
});
describe('update Method', function() {
- it('should call client put method with the appropriate uri', function(done) {
- var options = {
- relayWebhookId: "test"
+ it('should call client put method with the appropriate uri and payload', function() {
+ let webhook = {
+ name: 'New Replies Webhook'
};
- relayWebhooks.update(options, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('relay-webhooks/test');
- done();
- });
+ return relayWebhooks.update('test', webhook)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('relay-webhooks/test');
+ expect(client.put.firstCall.args[0].json).to.deep.equal(webhook);
+ });
});
- it('should throw an error if options is null', function(done) {
- relayWebhooks.update(null, function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if webhook.id is missing', function() {
+ return expect(relayWebhooks.update()).to.be.rejectedWith('id is required');
});
- it('should throw an error if options is missing', function(done) {
- relayWebhooks.update(function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.put).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if relayWebhookId is missing from options', function(done) {
- relayWebhooks.update({}, function(err) {
- expect(err.message).to.equal('relayWebhookId is required in options');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if webhook object is missing', function() {
+ return expect(relayWebhooks.update('test')).to.be.rejectedWith('webhook object is required');
});
});
describe('delete Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- relayWebhooks.delete('test', function(err, data) {
- expect(client.delete.firstCall.args[0].uri).to.equal('relay-webhooks/test');
- done();
- });
- });
-
- it('should throw an error if relayWebhookId is null', function(done) {
- relayWebhooks.delete(null, function(err) {
- expect(err.message).to.equal('relayWebhookId is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should call client delete method with the appropriate uri', function() {
+ return relayWebhooks.delete('test')
+ .then(function() {
+ expect(client.delete.firstCall.args[0].uri).to.equal('relay-webhooks/test');
+ });
});
- it('should throw an error if relayWebhookId is missing', function(done) {
- relayWebhooks.delete(function(err) {
- expect(err.message).to.equal('relayWebhookId is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(relayWebhooks.delete()).to.be.rejectedWith('id is required');
});
});
});
diff --git a/test/spec/sendingDomains.spec.js b/test/spec/sendingDomains.spec.js
index 512bc70..e8d3aa7 100644
--- a/test/spec/sendingDomains.spec.js
+++ b/test/spec/sendingDomains.spec.js
@@ -1,201 +1,124 @@
-var chai = require('chai')
+'use strict';
+
+var _ = require('lodash')
+ , chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Sending Domains Library', function() {
var client, sendingDomains;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields(),
- delete: sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
sendingDomains = require('../../lib/sendingDomains')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- sendingDomains.all(function() {
- expect(client.get.firstCall.args[0]).to.deep.equal({uri:'sending-domains'});
- done();
- });
+ describe('list', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return sendingDomains.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains'});
+ });
});
});
- describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- sendingDomains.find('test', function() {
- expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains/test'});
- done();
- });
+ describe('get', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return sendingDomains.get('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains/test'});
+ });
});
- it('should throw an error if domain is null', function(done) {
- sendingDomains.find(null, function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if domain is missing', function(done) {
- sendingDomains.find(function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(sendingDomains.get()).to.be.rejectedWith('domain is required');
});
});
- describe('create Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- var domainBody = {
- domain: "test"
+ describe('create', function() {
+ it('should call client post method with the appropriate uri and payload', function() {
+ var sendingDomain = {
+ domain: 'test'
};
- sendingDomains.create(domainBody, function(err, data) {
+ return sendingDomains.create(sendingDomain).then(function() {
expect(client.post.firstCall.args[0].uri).to.equal('sending-domains');
- done();
+ expect(client.post.firstCall.args[0].json).to.deep.equal(sendingDomain);
});
});
- it('should throw an error if domainBody is null', function(done) {
- sendingDomains.create(null, function(err) {
- expect(err.message).to.equal('domainBody is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if domainBody is missing', function(done) {
- sendingDomains.create(function(err) {
- expect(err.message).to.equal('domainBody is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if domain is missing from domainBody', function(done) {
- sendingDomains.create({}, function(err){
- expect(err.message).to.equal('domain is required in the domainBody');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if create options are missing', function() {
+ return expect(sendingDomains.create()).to.be.rejectedWith('create options are required');
});
});
- describe('update Method', function() {
- it('should call client put method with the appropriate uri', function(done) {
- var domainBody = {
- domain: "test"
+ describe('update', function() {
+ it('should call client put method with the appropriate uri and payload', function() {
+ var sendingDomain = {
+ tracking_domain: 'click.example1.com'
};
- sendingDomains.update(domainBody, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('sending-domains/test');
- done();
- });
+ return sendingDomains.update('test', sendingDomain)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('sending-domains/test');
+ expect(client.put.firstCall.args[0].json).to.deep.equal(_.omit(sendingDomain, 'domain'));
+ });
});
- it('should throw an error if domainBody is null', function(done) {
- sendingDomains.update(null, function(err) {
- expect(err.message).to.equal('domainBody is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if update options are missing', function() {
+ return expect(sendingDomains.update('test')).to.be.rejectedWith('update options are required');
});
- it('should throw an error if domainBody is missing', function(done) {
- sendingDomains.update(function(err) {
- expect(err.message).to.equal('domainBody is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if domain is missing from domainBody', function(done) {
- sendingDomains.update({}, function(err){
- expect(err.message).to.equal('domain is required in the domainBody');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(sendingDomains.update()).to.be.rejectedWith('domain is required');
});
});
- describe('delete Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- sendingDomains.delete('test', function(err, data) {
- expect(client.delete.firstCall.args[0].uri).to.equal('sending-domains/test');
- done();
- });
- });
-
- it('should throw an error if domain is null', function(done) {
- sendingDomains.delete(null, function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ describe('delete', function() {
+ it('should call client delete method with the appropriate uri', function() {
+ return sendingDomains.delete('test')
+ .then(function() {
+ expect(client.delete.firstCall.args[0].uri).to.equal('sending-domains/test');
+ });
});
- it('should throw an error if domain is missing', function(done) {
- sendingDomains.delete(function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(sendingDomains.delete()).to.be.rejectedWith('domain is required');
});
});
- describe('verify Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
+ describe('verify', function() {
+ it('should call client post method with the appropriate uri and payload', function() {
var options = {
- domain: 'test'
+ dkim_verify: true,
+ spf_verify: true
};
- sendingDomains.verify(options, function() {
- expect(client.post.firstCall.args[0].uri).to.equal('sending-domains/test/verify');
- done();
- });
- });
-
- it('should throw an error if domain is missing', function(done) {
- sendingDomains.verify(null, function(err) {
- expect(err.message).to.equal('domain is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ return sendingDomains.verify('test', options)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('sending-domains/test/verify');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(_.omit(options, 'domain'));
+ });
});
- it('should default verifyDKIM and verifySPF to be true', function(done) {
- var options = {
- domain: 'test'
- };
-
- sendingDomains.verify(options, function() {
- expect(client.post.firstCall.args[0].json.dkim_verify).to.be.true;
- expect(client.post.firstCall.args[0].json.spf_verify).to.be.true;
- done();
- });
+ it('should throw an error if domain is missing', function() {
+ return expect(sendingDomains.verify()).to.be.rejectedWith('domain is required');
});
- it('should allow a user to set verifyDKIM and verifySPF', function(done){
- var options = {
- domain: 'test',
- verifyDKIM: false,
- verifySPF: false
- };
-
- sendingDomains.verify(options, function() {
- expect(client.post.firstCall.args[0].json.dkim_verify).to.be.false;
- expect(client.post.firstCall.args[0].json.spf_verify).to.be.false;
- done();
- });
+ it('should throw an error if verification options are missing', function() {
+ return expect(sendingDomains.verify('test')).to.be.rejectedWith('verification options are required');
});
});
+
});
diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js
index 700510f..12ed294 100644
--- a/test/spec/sparkpost.spec.js
+++ b/test/spec/sparkpost.spec.js
@@ -1,12 +1,13 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
, sinon = require('sinon')
- , sinonChai = require('sinon-chai')
, zlib = require('zlib')
, nock = require('nock')
, SparkPost = require('../../lib/sparkpost');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
describe('SparkPost Library', function() {
@@ -65,6 +66,21 @@ describe('SparkPost Library', function() {
expect(client.origin).to.equal('https://dev.sparkpost.com');
});
+ it('should allow debug to be set in options', function() {
+ const key = '12345678901234567890';
+ let options = {}
+ , client;
+
+ // testing default initialization
+ client = new SparkPost(key, options);
+ expect(client.debug).to.equal(false);
+
+ // testing setting flag
+ options.debug = true;
+ client = new SparkPost(key, options);
+ expect(client.debug).to.equal(true);
+ });
+
describe('request method', function() {
var client;
@@ -94,11 +110,13 @@ describe('SparkPost Library', function() {
var options = {
method: 'GET'
, uri: 'get/test'
+ , json: true
+ , debug: true
};
client.request(options, function(err, data) {
// making sure original request was GET
- expect(data.request.method).to.equal('GET');
+ expect(data.debug.request.method).to.equal('GET');
// finish async test
done();
@@ -138,11 +156,8 @@ describe('SparkPost Library', function() {
};
client.request(options, function(err, data) {
- expect(data).to.be.defined;
expect(err).to.be.defined;
- expect(err.errors).to.deep.equal(data.body.errors);
-
// finish async test
done();
});
@@ -178,10 +193,12 @@ describe('SparkPost Library', function() {
var options = {
method: 'GET'
, uri: 'https://test.sparkpost.com/test'
+ , json: true
+ , debug: true
};
client.request(options, function(err, data) {
- expect(data.request.uri.href).to.equal('https://test.sparkpost.com/test');
+ expect(data.debug.request.uri.href).to.equal('https://test.sparkpost.com/test');
// finish async test
done();
@@ -196,9 +213,11 @@ describe('SparkPost Library', function() {
method: 'GET'
, uri: 'https://test.sparkpost.com/test'
, gzip: true
- };
+ , json: true
+ , debug: true
+ };
- zlib.gzip(TEST_MESSAGE+TEST_MESSAGE, function(err, gzipped) {
+ zlib.gzip(JSON.stringify({ msg: TEST_MESSAGE+TEST_MESSAGE }), function(err, gzipped) {
expect(err).to.be.null;
compressedMsg = gzipped;
gzipNock = nock('https://test.sparkpost.com', {
@@ -214,8 +233,8 @@ describe('SparkPost Library', function() {
});
client.request(options, function(err, data) {
expect(err).to.be.null;
- expect(data.statusCode).to.equal(200);
- expect(data.body).to.equal(TEST_MESSAGE + TEST_MESSAGE);
+ expect(data.debug.statusCode).to.equal(200);
+ expect(data.msg).to.equal(TEST_MESSAGE + TEST_MESSAGE);
// finish async test
done();
@@ -228,19 +247,21 @@ describe('SparkPost Library', function() {
nock('https://test.sparkpost.com')
.get('/test')
- .reply(200, TEST_MESSAGE);
+ .reply(200, { msg: TEST_MESSAGE });
var options = {
method: 'GET'
, uri: 'https://test.sparkpost.com/test'
, gzip: false
+ , json: true
+ , debug: true
};
client.request(options, function(err, data) {
expect(err).to.be.null;
- expect(data.statusCode).to.equal(200);
- expect(data.body).to.equal(TEST_MESSAGE);
- expect(data.headers).not.to.have.property('content-encoding');
+ expect(data.debug.statusCode).to.equal(200);
+ expect(data.msg).to.equal(TEST_MESSAGE);
+ expect(data.debug.headers).not.to.have.property('content-encoding');
// finish async test
done();
@@ -249,35 +270,68 @@ describe('SparkPost Library', function() {
});
describe('get method', function() {
- it('should deliver a GET + response', function(done) {
- var requestSpy = sinon.spy(SparkPost.prototype, 'request');
+ var client;
+ before(function() {
+ // setting up a client for all tests to use
var key = '12345678901234567890';
- var client = new SparkPost(key);
+ var options = {};
+
+ client = new SparkPost(key, options);
+ });
+
+ it('should deliver a GET + response', function(done) {
+ var requestSpy = sinon.spy(SparkPost.prototype, 'request');
nock('https://api.sparkpost.com')
.get('/api/v1/get/test')
.reply(200, { ok: true });
- client.get({uri: 'get/test'}, function(err, data) {
+ client.get({uri: 'get/test', debug: true}, function(err, data) {
// need to make sure we called request method
expect(requestSpy.calledOnce).to.be.true;
// making sure original request was GET
- expect(data.request.method).to.equal('GET');
+ expect(data.debug.request.method).to.equal('GET');
SparkPost.prototype.request.restore(); // restoring function
done();
});
});
+
+ it('should return a parsed JSON object', function(done) {
+ nock('https://test.sparkpost.com')
+ .get('/test')
+ .reply(200, '{ "ok": true }');
+
+ var options = {
+ uri: 'https://test.sparkpost.com/test'
+ };
+
+ client.get(options, function(err, data) {
+ expect(data).to.not.be.a('string');
+ expect(data).to.be.an('object');
+ expect(data).to.deep.equal({ok: true});
+
+ // finish async test
+ done();
+ });
+ });
});
describe('post method', function() {
- it('should deliver a POST', function(done) {
- var requestSpy = sinon.spy(SparkPost.prototype, 'request');
+ var client;
+ before(function() {
+ // setting up a client for all tests to use
var key = '12345678901234567890';
- var client = new SparkPost(key);
+ var options = {};
+
+ client = new SparkPost(key, options);
+ });
+
+ it('should deliver a POST', function(done) {
+ var requestSpy = sinon.spy(SparkPost.prototype, 'request');
nock('https://api.sparkpost.com')
.post('/api/v1/post/test')
@@ -288,6 +342,7 @@ describe('SparkPost Library', function() {
, json: {
testingData: 'test data'
}
+ , debug: true
};
client.post(reqOptions, function(err, data) {
@@ -295,20 +350,49 @@ describe('SparkPost Library', function() {
expect(requestSpy.calledOnce).to.be.true;
// making sure original request was POST
- expect(data.request.method).to.equal('POST');
+ expect(data.debug.request.method).to.equal('POST');
SparkPost.prototype.request.restore(); // restoring function
done();
});
});
+
+ it('should return a parsed JSON object', function(done) {
+ nock('https://test.sparkpost.com')
+ .post('/test')
+ .reply(200, '{ "ok": true }');
+
+ var options = {
+ uri: 'https://test.sparkpost.com/test'
+ , json: {
+ testingData: 'test data'
+ }
+ };
+
+ client.post(options, function(err, data) {
+ expect(data).to.not.be.a('string');
+ expect(data).to.be.an('object');
+ expect(data).to.deep.equal({ok: true});
+
+ // finish async test
+ done();
+ });
+ });
});
describe('put method', function() {
- it('should deliever a PUT/UPDATE', function(done) {
- var requestSpy = sinon.spy(SparkPost.prototype, 'request');
+ var client;
+ before(function() {
+ // setting up a client for all tests to use
var key = '12345678901234567890';
- var client = new SparkPost(key);
+ var options = {};
+
+ client = new SparkPost(key, options);
+ });
+
+ it('should deliver a PUT/UPDATE', function(done) {
+ var requestSpy = sinon.spy(SparkPost.prototype, 'request');
nock('https://api.sparkpost.com')
.put('/api/v1/put/test')
@@ -319,6 +403,7 @@ describe('SparkPost Library', function() {
, json: {
testingData: 'test data'
}
+ , debug: true
};
client.put(reqOptions, function(err, data) {
@@ -326,20 +411,49 @@ describe('SparkPost Library', function() {
expect(requestSpy.calledOnce).to.be.true;
// making sure original request was PUT
- expect(data.request.method).to.equal('PUT');
+ expect(data.debug.request.method).to.equal('PUT');
SparkPost.prototype.request.restore(); // restoring function
done();
});
});
+
+ it('should return a parsed JSON object', function(done) {
+ nock('https://test.sparkpost.com')
+ .put('/test')
+ .reply(200, '{ "ok": true }');
+
+ var options = {
+ uri: 'https://test.sparkpost.com/test'
+ , json: {
+ testingData: 'test data'
+ }
+ };
+
+ client.put(options, function(err, data) {
+ expect(data).to.not.be.a('string');
+ expect(data).to.be.an('object');
+ expect(data).to.deep.equal({ok: true});
+
+ // finish async test
+ done();
+ });
+ });
});
describe('delete method', function() {
- it('should deliever a DELETE', function(done) {
- var requestSpy = sinon.spy(SparkPost.prototype, 'request');
+ var client;
+ before(function() {
+ // setting up a client for all tests to use
var key = '12345678901234567890';
- var client = new SparkPost(key);
+ var options = {};
+
+ client = new SparkPost(key, options);
+ });
+
+ it('should deliver a DELETE', function(done) {
+ var requestSpy = sinon.spy(SparkPost.prototype, 'request');
nock('https://api.sparkpost.com')
.delete('/api/v1/delete/test')
@@ -350,6 +464,7 @@ describe('SparkPost Library', function() {
, json: {
testingData: 'test data'
}
+ , debug: true
};
client.delete(reqOptions, function(err, data) {
@@ -357,11 +472,33 @@ describe('SparkPost Library', function() {
expect(requestSpy.calledOnce).to.be.true;
// making sure original request was DELETE
- expect(data.request.method).to.equal('DELETE');
+ expect(data.debug.request.method).to.equal('DELETE');
SparkPost.prototype.request.restore(); // restoring function
done();
});
});
+
+ it('should return a parsed JSON object', function(done) {
+ nock('https://test.sparkpost.com')
+ .delete('/test')
+ .reply(200, '{ "ok": true }');
+
+ var options = {
+ uri: 'https://test.sparkpost.com/test'
+ , json: {
+ testingData: 'test data'
+ }
+ };
+
+ client.delete(options, function(err, data) {
+ expect(data).to.not.be.a('string');
+ expect(data).to.be.an('object');
+ expect(data).to.deep.equal({ok: true});
+
+ // finish async test
+ done();
+ });
+ });
});
});
diff --git a/test/spec/subaccounts.spec.js b/test/spec/subaccounts.spec.js
index d36d873..b4cec81 100644
--- a/test/spec/subaccounts.spec.js
+++ b/test/spec/subaccounts.spec.js
@@ -1,220 +1,90 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
-describe('Subaccounts Library', function () {
- var client, subaccounts;
+describe('Subaccounts Library', function() {
+ let client, subaccounts;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({})
};
subaccounts = require('../../lib/subaccounts')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- subaccounts.all(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('subaccounts');
- done();
- });
+ describe('list Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return subaccounts.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('subaccounts');
+ });
});
});
- describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var subaccountId = 'test';
-
- subaccounts.find(subaccountId, function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('subaccounts/test');
- done();
- });
+ describe('get Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return subaccounts.get('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('subaccounts/test');
+ });
});
- it('should throw an error if subaccountId is null', function(done) {
- subaccounts.find(null, function(err) {
- expect(err.message).to.equal('subaccountId is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if subaccountId is missing', function(done) {
- subaccounts.find(function(err) {
- expect(err.message).to.equal('subaccountId is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(subaccounts.get()).to.be.rejectedWith('id is required');
});
});
describe('create Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- var options = {
- name: 'test',
- keyLabel: 'test',
- keyGrants: []
- };
-
- subaccounts.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('subaccounts');
- done();
- });
- });
-
- it('should throw an error if options is null', function(done) {
- subaccounts.create(null, function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if options is missing', function(done) {
- subaccounts.create(function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if name is missing from options', function(done) {
- var options = {
- keyLabel: 'test',
- keyGrants: []
- };
-
- subaccounts.create(options, function(err) {
- expect(err.message).to.equal('name is required in options');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if keyLabel is missing from options', function(done) {
- var options = {
- name: 'test',
- keyGrants: []
- };
-
- subaccounts.create(options, function(err) {
- expect(err.message).to.equal('keyLabel is required in options');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if keyGrants is missing from options', function(done) {
- var options = {
- name: 'test',
- keyLabel: 'test'
- };
-
- subaccounts.create(options, function(err) {
- expect(err.message).to.equal('keyGrants is required in options');
- expect(client.post).not.to.have.been.called;
- done();
- });
- });
-
- it('should not set key_valid_ips in request if keyValidIps is missing from options', function(done) {
- var options = {
- name: 'test',
- keyLabel: 'test',
- keyGrants: []
- };
-
- subaccounts.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].json.key_valid_ips).to.be.undefined;
- done();
- })
- });
-
- it('should not set key_valid_ips in request if keyValidIps is empty array', function(done) {
- var options = {
+ it('should call client post method with the appropriate uri and payload', function() {
+ var subaccount = {
name: 'test',
- keyLabel: 'test',
- keyGrants: [],
- keyValidIps: []
+ key_label: 'test',
+ key_grants: []
};
- subaccounts.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].json.key_valid_ips).to.be.undefined;
- done();
- })
+ return subaccounts.create(subaccount)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('subaccounts');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(subaccount);
+ });
});
- it('should set key_valid_ips in request if keyValidIps is in options and is a non-empty array', function(done) {
- var options = {
- name: 'test',
- keyLabel: 'test',
- keyGrants: [],
- keyValidIps: ['127.0.0.1']
- };
-
- subaccounts.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].json.key_valid_ips).to.eql(['127.0.0.1']);
- done();
- })
- });
-
- it('should set key_valid_ips in request if keyValidIps is in options and is not an array', function(done) {
- var options = {
- name: 'test',
- keyLabel: 'test',
- keyGrants: [],
- keyValidIps: '127.0.0.1'
- };
-
- subaccounts.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].json.key_valid_ips).to.eql(['127.0.0.1']);
- done();
- })
+ it('should throw an error if subaccount object is missing', function() {
+ return expect(subaccounts.create()).to.be.rejectedWith('subaccount object is required');
});
});
describe('update Method', function() {
- it('should call client put method with the appropriate uri', function(done) {
- var options = {
- subaccountId: 'test'
+ it('should call client put method with the appropriate uri and payload', function() {
+ var subaccount = {
+ name: 'Hey Joe! Garage and Parts',
+ status: 'suspended',
+ ip_pool: ''
};
- subaccounts.update(options, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('subaccounts/test');
- done();
- });
+ return subaccounts.update('test', subaccount)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('subaccounts/test');
+ expect(client.put.firstCall.args[0].json).to.deep.equal(subaccount);
+ });
});
- it('should throw an error if options is null', function(done) {
- subaccounts.update(null, function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if subaccount id is missing from options', function() {
+ return expect(subaccounts.update()).to.be.rejectedWith('id is required');
});
- it('should throw an error if options is missing', function(done) {
- subaccounts.update(function(err) {
- expect(err.message).to.equal('options are required');
- expect(client.put).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if subaccountId is missing from options', function(done) {
- var options = {};
-
- subaccounts.update(options, function(err, data) {
- expect(err.message).to.equal('subaccountId is required in options');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if subaccount object is missing', function() {
+ return expect(subaccounts.update('test')).to.be.rejectedWith('subaccount object is required');
});
});
});
diff --git a/test/spec/suppressionList.spec.js b/test/spec/suppressionList.spec.js
index a661f11..f28be3b 100644
--- a/test/spec/suppressionList.spec.js
+++ b/test/spec/suppressionList.spec.js
@@ -1,119 +1,90 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Suppression List Library', function() {
- var client, suppressionList;
+ let client, suppressionList;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields(),
- 'delete': sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
suppressionList = require('../../lib/suppressionList')(client);
});
- describe('search Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- suppressionList.search({limit: 5}, function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('suppression-list');
- done();
- });
+ describe('list', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return suppressionList.list({limit: 5})
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('suppression-list');
+ });
});
});
- describe('checkStatus Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- suppressionList.checkStatus('test@test.com', function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('suppression-list/test@test.com');
- done();
- });
+ describe('get', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return suppressionList.get('test@test.com')
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('suppression-list/test@test.com');
+ });
});
- it('should throw an error if email is null', function(done) {
- suppressionList.checkStatus(null, function(err) {
- expect(err.message).to.equal('email is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if email is missing', function(done) {
- suppressionList.checkStatus(function(err) {
- expect(err.message).to.equal('email is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if email is missing', function() {
+ return expect(suppressionList.get()).to.be.rejectedWith('email is required');
});
});
- describe('removeStatus Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- suppressionList.removeStatus('test@test.com', function(err, data) {
- expect(client['delete'].firstCall.args[0].uri).to.equal('suppression-list/test@test.com');
- done();
- });
- });
-
- it('should throw an error if email is null', function(done) {
- suppressionList.removeStatus(null, function(err) {
- expect(err.message).to.equal('email is required');
- expect(client['delete']).not.to.have.been.called;
- done();
- });
- });
+ describe('upsert', function() {
+ it('should accept a single list entry', function() {
+ var listEntry = { email: 'test@test.com' };
- it('should throw an error if email is missing', function(done) {
- suppressionList.removeStatus(function(err) {
- expect(err.message).to.equal('email is required');
- expect(client['delete']).not.to.have.been.called;
- done();
- });
+ return suppressionList.upsert(listEntry)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('suppression-list');
+ expect(client.put.firstCall.args[0].json.recipients).to.deep.equal([listEntry]);
+ });
});
- });
- describe('upsert Method', function() {
- it('should accept an array of recipients', function(done) {
- var recipients = [
+ it('should accept an array of list entries', function() {
+ var listEntries = [
{ email: 'test1@test.com' },
{ email: 'test2@test.com' }
];
- suppressionList.upsert(recipients, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('suppression-list');
- expect(client.put.firstCall.args[0].json.recipients).to.deep.equal(recipients);
- done();
- });
+ return suppressionList.upsert(listEntries)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('suppression-list');
+ expect(client.put.firstCall.args[0].json.recipients).to.deep.equal(listEntries);
+ });
});
- it('should throw an error if recipient is null', function(done) {
- suppressionList.upsert(null, function(err) {
- expect(err.message).to.equal('recipient is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if recipient is missing', function() {
+ return expect(suppressionList.upsert()).to.be.rejectedWith('list entries is required');
});
+ });
- it('should throw an error if recipient is missing', function(done) {
- suppressionList.upsert(function(err) {
- expect(err.message).to.equal('recipient is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ describe('delete', function() {
+ it('should call client delete method with the appropriate uri', function() {
+ return suppressionList.delete('test@test.com')
+ .then(function() {
+ expect(client.delete.firstCall.args[0].uri).to.equal('suppression-list/test@test.com');
+ });
});
- it('should upsert a single recipient as an array', function(done) {
- var recipient = { email: 'test1@test.com' };
- suppressionList.upsert(recipient, function(err, data) {
- expect(client.put.firstCall.args[0].json.recipients).to.deep.equal([recipient]);
- done();
- });
+ it('should throw an error if email deleteEntry missing', function() {
+ return expect(suppressionList.delete()).to.be.rejectedWith('email is required');
});
});
+
});
diff --git a/test/spec/templates.spec.js b/test/spec/templates.spec.js
index 4043f2c..a0760bc 100644
--- a/test/spec/templates.spec.js
+++ b/test/spec/templates.spec.js
@@ -1,179 +1,183 @@
-var chai = require('chai')
+'use strict';
+
+var _ = require('lodash')
+ , chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Templates Library', function() {
var client, templates;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields(),
- 'delete': sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
templates = require('../../lib/templates')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- templates.all(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('templates');
- done();
- });
+ describe('list Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return templates.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('templates');
+ });
});
});
- describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
- templates.find(options, function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('templates/test');
- done();
- });
+ describe('get Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ var id = 'test';
+ return templates.get(id)
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('templates/test');
+ });
});
- it('should throw an error if id is missing', function(done) {
- templates.find(null, function(err) {
- expect(err.message).to.equal('template id is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(templates.get()).to.be.rejectedWith('template id is required');
});
- it('should allow draft to be set in options', function(done) {
- var options = {
- id: 'test',
- draft: true
- };
+ it('should allow draft to be set in options', function() {
+ var id = 'test'
+ , options = {
+ draft: true
+ };
- templates.find(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({draft: true});
- done();
- });
+
+ return templates.get(id, options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({draft: true});
+ });
});
});
describe('create Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- var options = {
- template: {
- id: "test"
- }
+ it('should call client post method with the appropriate uri and payload', function() {
+ var template = {
+ id: 'test'
};
- templates.create(options, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('templates');
- done();
- });
+ return templates.create(template)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('templates');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(template);
+ });
});
- it('should throw an error if id is missing', function(done) {
- templates.create(null, function(err) {
- expect(err.message).to.equal('template object is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if template object is missing', function() {
+ return expect(templates.create()).to.be.rejectedWith('template object is required');
});
});
describe('update Method', function() {
- it('should call client put method with the appropriate uri', function(done) {
- var options = {
- template: {
- id: "test"
- }
- };
-
- templates.update(options, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('templates/test');
- done();
- });
+ it('should call client put method with the appropriate uri and payload', function() {
+ var id = 'test'
+ , template = {
+ name: 'A new name!'
+ };
+
+ return templates.update(id, template)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('templates/test');
+ expect(client.put.firstCall.args[0].json).to.deep.equal(template);
+ });
});
- it('should throw an error if id is missing', function(done) {
- templates.update(null, function(err) {
- expect(err.message).to.equal('template object is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if template id is missing', function() {
+ return expect(templates.update()).to.be.rejectedWith('template id is required');
});
- it('should allow update_published to be set in options', function(done) {
- var options = {
- template: {
- id: "test"
- },
- update_published: true
- };
+ it('should throw an error if template object is missing', function() {
+ return expect(templates.update('test')).to.be.rejectedWith('template object is required');
+ });
- templates.update(options, function(err, data) {
- expect(client.put.firstCall.args[0].qs).to.deep.equal({update_published: true});
- done();
+ it('should not throw an error if optional 3nd argument is a function (callback)', function() {
+ let cb = sinon.stub()
+ , id = 'test'
+ , template = {
+ name: 'A new name!'
+ };
+ return templates.update(id, template, cb).then(function() {
+ expect(cb.callCount).to.equal(1);
});
});
- });
- describe('delete Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- templates['delete']('test', function(err, data) {
- expect(client['delete'].firstCall.args[0].uri).to.equal('templates/test');
- done();
- });
+ it('should allow update_published to be set in options', function() {
+ var id = 'test'
+ , template = {
+ name: 'Test Template'
+ }
+ , options = {
+ update_published: true
+ };
+
+ return templates.update(id, template, options)
+ .then(function() {
+ expect(client.put.firstCall.args[0].qs).to.deep.equal(options);
+ });
});
+ });
- it('should throw an error if id is null', function(done) {
- templates['delete'](null, function(err) {
- expect(err.message).to.equal('template id is required');
- expect(client['delete']).not.to.have.been.called;
- done();
- });
+ describe('delete Method', function() {
+ it('should call client delete method with the appropriate uri', function() {
+ return templates.delete('test')
+ .then(function() {
+ expect(client.delete.firstCall.args[0].uri).to.equal('templates/test');
+ });
});
- it('should throw an error if id is missing', function(done) {
- templates['delete'](function(err) {
- expect(err.message).to.equal('template id is required');
- expect(client['delete']).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(templates.delete()).to.be.rejectedWith('template id is required');
});
});
describe('preview Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
- templates.preview(options, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('templates/test/preview');
- done();
- });
+ it('should call client post method with the appropriate uri and payload', function() {
+ var id = 'test'
+ , options = {
+ substitution_data: {
+ 'name': 'Natalie',
+ 'age': 35,
+ 'member': true
+ }
+ };
+ return templates.preview(id, options)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('templates/test/preview');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(options);
+ });
});
- it('should throw an error if id is missing', function(done) {
- templates.preview(null, function(err) {
- expect(err.message).to.equal('template id is required');
- expect(client.post).not.to.have.been.called;
- done();
+ it('should throw an error if id is missing', function() {
+ return expect(templates.preview()).to.be.rejectedWith('template id is required');
+ });
+
+ it('should not throw an error if optional 2nd argument is a function (callback)', function() {
+ let cb = sinon.stub();
+ return templates.preview('test', cb).then(function() {
+ expect(cb.callCount).to.equal(1);
});
});
- it('should allow draft to be set in options', function(done) {
- var options = {
- id: 'test',
- draft: true
- };
+ it('should allow draft to be set in options', function() {
+ var id = 'test'
+ , options = {
+ draft: true
+ };
- templates.preview(options, function(err, data) {
- expect(client.post.firstCall.args[0].qs).to.deep.equal({draft: true});
- done();
- });
+ return templates.preview(id, options)
+ .then(function() {
+ expect(client.post.firstCall.args[0].qs).to.deep.equal({draft: true});
+ });
});
});
});
diff --git a/test/spec/toApiFormat.spec.js b/test/spec/toApiFormat.spec.js
deleted file mode 100644
index 02aa250..0000000
--- a/test/spec/toApiFormat.spec.js
+++ /dev/null
@@ -1,184 +0,0 @@
-'use strict';
-
-var chai = require('chai')
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai')
- , toApiFormat = require('../../lib/toApiFormat')
- , expect = chai.expect
- , _ = require('lodash')
- ;
-
-chai.use(sinonChai);
-
-describe('toApiFormat', function() {
- it('should recursively convert complex object keys to snake_case', function(done) {
- var testObj = {
- simpleString: "foo"
- , boolVal: true
- , numBers: 201
- , bangObj: {
- strTwo: "bar"
- , string_three: "skip"
- }
- , recipients: [
- {name: 'John Doe', address: 'j.doe@sparkpost.com'}
- , {name: 'Sam Jones', address: 's.jones@sparkpost.com'}
- ]
- , content: {
- email_rfc822: 'a message'
- }
- , fizzArr: [
- {
- buzzInga: "buzz"
- , bang: {
- bellHop: "bell"
- }
- }
- , {
- bilBo: "baggins"
- , alias: {
- misTer: "underhill"
- }
- }
- ]
- , good_name: null
- };
-
- var validationObj = {
- simple_string: "foo"
- , bool_val: true
- , num_bers: 201
- , bang_obj: {
- str_two: "bar"
- , string_three: "skip"
- }
- , recipients: [
- {name: 'John Doe', address: 'j.doe@sparkpost.com'}
- , {name: 'Sam Jones', address: 's.jones@sparkpost.com'}
- ]
- , content: {
- email_rfc822: 'a message'
- }
- , fizz_arr: [
- {
- buzz_inga: "buzz"
- , bang: {
- bell_hop: "bell"
- }
- }
- , {
- bil_bo: "baggins"
- , alias: {
- mis_ter: "underhill"
- }
- }
- ]
- , good_name: null
- };
-
- var out = toApiFormat(testObj);
-
- expect(out).to.deep.equal(validationObj);
-
- done();
- });
-
- it('should throw an error if it encounters one', function(done) {
- var stub = sinon.stub(_, 'snakeCase').throws();
-
- var testObj = {
- simpleString: "foo"
- , substitution_data: {
- key1: 'value1',
- key_2: 'value_2'
- }
- , sampleArray: [
- 'oneTag',
- 'two_tag',
- 'substitution_data',
- 'tags'
- ]
- };
-
- try {
- var out = toApiFormat(testObj);
- } catch(e) {
- expect(e).to.not.be.null;
- }
-
- stub.restore();
- done();
- });
-
- it('should ignore sub-properties of properties on exclude list', function(done) {
- var testObj = {
- simpleString: "foo"
- , substitution_data: {
- key1: 'value1',
- key_2: 'value_2'
- }
- , sampleArray: [
- {
- goodValue: 'hello',
- tags: [
- 'oneTag',
- 'two_tag',
- 'substitution_data',
- 'tags'
- ]
- }
- ]
- };
-
- var validationObj = {
- simple_string: "foo"
- , substitution_data: {
- key1: 'value1',
- key_2: 'value_2'
- }
- , sample_array: [
- {
- good_value: 'hello',
- tags: [
- 'oneTag',
- 'two_tag',
- 'substitution_data',
- 'tags'
- ]
- }
- ]
- };
-
- var out = toApiFormat(testObj);
-
- expect(out).to.deep.equal(validationObj);
-
- done();
- });
-
- it('should preserve objects with number properties', function(done) {
- var testObj = {
- array: [ 0, 1, , , , 5, 6]
- , object: {
- "0": 0,
- "1": 1,
- "5": 5,
- "6": 6
- }
- , substitution_data: {
- "0": 0,
- "1": 1,
- "5": 5,
- "6": 6
- }
- , tags: [ 0, 1, , , , 5, 6]
- };
-
-
- var out = toApiFormat(_.clone(testObj));
-
- expect(out).to.deep.equal(testObj);
-
- done();
- });
-});
diff --git a/test/spec/transmissions.spec.js b/test/spec/transmissions.spec.js
index bbe50e3..08fc0f0 100644
--- a/test/spec/transmissions.spec.js
+++ b/test/spec/transmissions.spec.js
@@ -1,127 +1,129 @@
+'use strict';
+
var chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Transmissions Library', function() {
- var client, transmission;
+ var client, transmissions;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({})
};
- transmission = require('../../lib/transmissions')(client);
+ transmissions = require('../../lib/transmissions')(client);
});
describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- transmission.all(function() {
+ it('should call client get method with the appropriate uri', function() {
+ return transmissions.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('transmissions');
+ });
+ });
+
+ it('should call client get method with the appropriate uri using callback', function(done) {
+ transmissions.list(function() {
expect(client.get.firstCall.args[0].uri).to.equal('transmissions');
done();
});
});
- it('should allow campaign_id to be set in options', function(done) {
+ it('should allow campaign_id to be set in options', function() {
var options = {
campaign_id: 'test-campaign'
};
- transmission.all(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'});
- done();
- });
+ return transmissions.list(options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'});
+ });
});
- it('should allow template_id to be set in options', function(done) {
+ it('should allow template_id to be set in options', function() {
var options = {
template_id: 'test-template'
};
- transmission.all(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'});
- done();
- });
+ return transmissions.list(options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'});
+ });
});
});
describe('find Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- transmission.find('test', function() {
- expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'});
- done();
- });
+ it('should call client get method with the appropriate uri', function() {
+ return transmissions.get('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'});
+ });
});
- it('should throw an error if transmissionID is null', function(done) {
- transmission.find(null, function(err) {
- expect(err.message).to.equal('transmissionID is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
- });
-
- it('should throw an error if transmissionID is missing', function(done) {
- transmission.find(function(err) {
- expect(err.message).to.equal('transmissionID is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(transmissions.get()).to.be.rejectedWith('id is required');
});
});
describe('send Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- var options = {
- transmissionBody: {
- campaign: 'test-campaign'
- }
+ it('should call client post method with the appropriate uri and payload', function() {
+ var transmission = {
+ campaign_id: 'test-campaign'
};
- transmission.send(options, function() {
- expect(client.post.firstCall.args[0].uri).to.equal('transmissions');
- done();
- });
+ return transmissions.send(transmission)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('transmissions');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(transmission);
+ });
});
- it('should throw an error if transmissionBody is missing', function(done) {
- transmission.send(null, function(err) {
- expect(err.message).to.equal('transmissionBody is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if transmission object is missing', function() {
+ return expect(transmissions.send(function() {})).to.be.rejectedWith('transmission object is required');
});
- it('should allow num_rcpt_errors to be set in options', function(done) {
- var options = {
- transmissionBody: {
- campaign: 'test-campaign'
- },
- num_rcpt_errors: 3
- };
+ it('should allow num_rcpt_errors to be set in options', function() {
+ var transmission = {
+ campaign_id: 'test-campaign'
+ }
+ , options = {
+ num_rcpt_errors: 3
+ };
+
+ return transmissions.send(transmission, options)
+ .then(function() {
+ expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3});
+ });
+ });
- transmission.send(options, function(err, data) {
- expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3});
- done();
+ it('should not throw an error if optional 2nd argument is a function (callback)', function() {
+ let cb = sinon.stub()
+ , transmission = {
+ campaign_id: 'test-campaign'
+ };
+ return transmissions.send(transmission, cb).then(function() {
+ expect(cb.callCount).to.equal(1);
});
});
- it('should leave email_rfc822 content keys intact', function(done) {
+ it('should leave email_rfc822 content keys intact', function() {
var options = {
- transmissionBody: {
- content: {
- email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World'
- }
+ content: {
+ email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World'
}
};
- transmission.send(options, function(err, data) {
- expect(client.post.firstCall.args[0].json.content).to.have.property('email_rfc822');
- done();
- });
+ return transmissions.send(options)
+ .then(function() {
+ expect(client.post.firstCall.args[0].json.content).to.have.property('email_rfc822');
+ });
});
});
});
diff --git a/test/spec/webhooks.spec.js b/test/spec/webhooks.spec.js
index 1394d0f..2f79d49 100644
--- a/test/spec/webhooks.spec.js
+++ b/test/spec/webhooks.spec.js
@@ -1,267 +1,204 @@
-var chai = require('chai')
+'use strict';
+
+var _ = require('lodash')
+ , chai = require('chai')
, expect = chai.expect
- , sinon = require('sinon')
- , sinonChai = require('sinon-chai');
+ , sinon = require('sinon');
+
+require('sinon-as-promised');
-chai.use(sinonChai);
+chai.use(require('sinon-chai'));
+chai.use(require('chai-as-promised'));
describe('Webhooks Library', function() {
var client, webhooks;
beforeEach(function() {
client = {
- get: sinon.stub().yields(),
- post: sinon.stub().yields(),
- put: sinon.stub().yields(),
- delete: sinon.stub().yields()
+ get: sinon.stub().resolves({}),
+ post: sinon.stub().resolves({}),
+ put: sinon.stub().resolves({}),
+ delete: sinon.stub().resolves({})
};
webhooks = require('../../lib/webhooks')(client);
});
- describe('all Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- webhooks.all(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('webhooks');
- done();
- });
+ describe('list Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return webhooks.list()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('webhooks');
+ });
});
- it('should allow timezone to be set in options', function(done) {
+ it('should allow timezone to be set in options', function() {
var options = {
timezone: 'America/New_York'
};
- webhooks.all(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'});
- done();
- });
+ return webhooks.list(options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'});
+ });
});
});
- describe('describe Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
-
- webhooks.describe(options, function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test');
- done();
- });
+ describe('get Method', function() {
+ it('should call client get method with the appropriate uri', function() {
+ return webhooks.get('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test');
+ });
});
- it('should throw an error if id is missing', function(done) {
- webhooks.describe(null, function(err) {
- expect(err.message).to.equal('id is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(webhooks.get()).to.be.rejectedWith('id is required');
});
- it('should allow timezone to be set in options', function(done) {
+ it('should allow timezone to be set in options', function() {
var options = {
- id: 'test',
timezone: 'America/New_York'
};
- webhooks.describe(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'});
- done();
- });
+ return webhooks.get('test', options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'});
+ });
});
});
describe('create Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
- webhooks.create({}, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('webhooks');
- done();
- });
- });
+ it('should call client post method with the appropriate uri and payload', function() {
+ var webhook = {
+ name: 'Example webhook',
+ target: 'http://client.example.com/example-webhook',
+ events: ['delivery', 'injection', 'open', 'click']
+ };
- it('should throw an error if webhook is null', function(done) {
- webhooks.create(null, function(err) {
- expect(err.message).to.equal('webhook object is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ return webhooks.create(webhook)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('webhooks');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(webhook);
+ });
});
- it('should throw an error if webhook is missing', function(done) {
- webhooks.create(function(err) {
- expect(err.message).to.equal('webhook object is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if webhook is missing', function() {
+ return expect(webhooks.create()).to.be.rejectedWith('webhook object is required');
});
});
describe('update Method', function() {
- it('should call client put method with the appropriate uri', function(done) {
+ it('should call client put method with the appropriate uri', function() {
var webhook = {
- id: "test"
+ name: 'Renamed webhook',
+ events: ['rejection', 'delay'],
+ auth_type: 'none'
};
- webhooks.update(webhook, function(err, data) {
- expect(client.put.firstCall.args[0].uri).to.equal('webhooks/test');
- done();
- });
- });
-
- it('should throw an error if webhook is null', function(done) {
- webhooks.update(null, function(err) {
- expect(err.message).to.equal('webhook object is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ return webhooks.update('test', webhook)
+ .then(function() {
+ expect(client.put.firstCall.args[0].uri).to.equal('webhooks/test');
+ expect(client.put.firstCall.args[0].json).to.deep.equal(webhook);
+ });
});
- it('should throw an error if webhook is missing', function(done) {
- webhooks.update(function(err) {
- expect(err.message).to.equal('webhook object is required');
- expect(client.put).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(webhooks.update()).to.be.rejectedWith('id is required');
});
- it('should throw an error if webhook.id is missing', function(done) {
- webhooks.update({}, function (err) {
- expect(err.message).to.equal('webhook.id is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if webhook is missing', function() {
+ return expect(webhooks.update('test')).to.be.rejectedWith('webhook object is required');
});
});
describe('delete Method', function() {
- it('should call client delete method with the appropriate uri', function(done) {
- webhooks.delete('test', function(err, data) {
- expect(client.delete.firstCall.args[0].uri).to.equal('webhooks/test');
- done();
- });
- });
-
- it('should throw an error if id is null', function(done) {
- webhooks.delete(null, function(err) {
- expect(err.message).to.equal('id is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should call client delete method with the appropriate uri', function() {
+ return webhooks.delete('test')
+ .then(function() {
+ expect(client.delete.firstCall.args[0].uri).to.equal('webhooks/test');
+ });
});
- it('should throw an error if id is missing', function(done) {
- webhooks.delete(function(err) {
- expect(err.message).to.equal('id is required');
- expect(client.delete).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(webhooks.delete()).to.be.rejectedWith('id is required');
});
});
describe('validate Method', function() {
- it('should call client post method with the appropriate uri', function(done) {
+ it('should call client post method with the appropriate uri and payload', function() {
var options = {
- id: 'test',
message: {
msys: {}
}
};
- webhooks.validate(options, function(err, data) {
- expect(client.post.firstCall.args[0].uri).to.equal('webhooks/test/validate');
- done();
- });
+ return webhooks.validate('test', options)
+ .then(function() {
+ expect(client.post.firstCall.args[0].uri).to.equal('webhooks/test/validate');
+ expect(client.post.firstCall.args[0].json).to.deep.equal(options);
+ });
});
- it('should throw an error if id is missing', function(done) {
- webhooks.validate(null, function (err) {
- expect(err.message).to.equal('id is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(webhooks.validate()).to.be.rejectedWith('id is required');
});
- it('should throw an error if message is missing', function(done) {
- var options = {
- id: 'test'
- };
-
- webhooks.validate(options, function (err) {
- expect(err.message).to.equal('message is required');
- expect(client.post).not.to.have.been.called;
- done();
- });
+ it('should throw an error if message is missing', function() {
+ return expect(webhooks.validate('test')).to.be.rejectedWith('message is required');
});
});
describe('getBatchStatus Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
-
- webhooks.getBatchStatus(options, function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test/batch-status');
- done();
- });
+ it('should call client get method with the appropriate uri', function() {
+ return webhooks.getBatchStatus('test')
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test/batch-status');
+ });
});
- it('should throw an error if id is missing', function(done) {
- webhooks.getBatchStatus(null, function (err) {
- expect(err.message).to.equal('id is required');
- expect(client.get).not.to.have.been.called;
- done();
- });
+ it('should throw an error if id is missing', function() {
+ return expect(webhooks.getBatchStatus()).to.be.rejectedWith('id is required');
});
- it('should allow limit to be set in options', function(done) {
+ it('should allow limit to be set in options', function() {
var options = {
- id: 'test',
limit: 1000
};
- webhooks.getBatchStatus(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({limit: 1000});
- done();
- });
+ return webhooks.getBatchStatus('test', options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({limit: 1000});
+ });
});
});
describe('getDocumentation Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
-
- webhooks.getDocumentation(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/documentation');
- done();
- });
+ it('should call client get method with the appropriate uri', function() {
+ return webhooks.getDocumentation()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/documentation');
+ });
});
});
describe('getSamples Method', function() {
- it('should call client get method with the appropriate uri', function(done) {
- var options = {
- id: 'test'
- };
-
- webhooks.getSamples(function(err, data) {
- expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/samples');
- done();
- });
+ it('should call client get method with the appropriate uri', function() {
+ return webhooks.getSamples()
+ .then(function() {
+ expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/samples');
+ });
});
- it('should allow events to be set in options', function(done) {
+ it('should allow events to be set in options', function() {
var options = {
events: 'bounces'
};
- webhooks.getSamples(options, function(err, data) {
- expect(client.get.firstCall.args[0].qs).to.deep.equal({events: 'bounces'});
- done();
- });
+ return webhooks.getSamples(options)
+ .then(function() {
+ expect(client.get.firstCall.args[0].qs).to.deep.equal({events: 'bounces'});
+ });
});
});
});