From 598affbca2857ca3f4cdd9c928852dce64894c72 Mon Sep 17 00:00:00 2001 From: "Aydrian J. Howard" Date: Tue, 22 Mar 2016 10:41:37 -0400 Subject: [PATCH 01/27] Added json flag to base request and tests to check for JSON response --- lib/sparkpost.js | 3 + test/spec/sparkpost.spec.js | 143 ++++++++++++++++++++++++++++++++---- 2 files changed, 133 insertions(+), 13 deletions(-) diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 0f2ce9f..c02807a 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -85,6 +85,9 @@ SparkPost.prototype.request = function( options, callback ) { // set Strict SSL (Always true) options.strictSSL = true; + // set JSON (Always true) + options.json = true; + // default to accepting gzipped responses if (typeof options.gzip === 'undefined') { options.gzip = true; diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 56ba899..2a5cbc4 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -194,7 +194,7 @@ describe('SparkPost Library', function() { expect(err).to.be.null; expect(data.statusCode).to.equal(200); expect(data.body).to.equal(TEST_MESSAGE + TEST_MESSAGE); - + // finish async test done(); }); @@ -227,11 +227,18 @@ 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') @@ -248,14 +255,41 @@ describe('SparkPost Library', function() { done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .get('/test') + .reply(200, '{ "ok": true }'); + + var options = { + method: 'GET' + , uri: 'https://test.sparkpost.com/test' + }; + + client.request(options, function(err, data) { + expect(data.body).to.not.be.a('string'); + expect(data.body).to.be.an('object'); + expect(data.body).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') @@ -279,14 +313,44 @@ describe('SparkPost Library', function() { done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .post('/test') + .reply(200, '{ "ok": true }'); + + var options = { + method: 'POST' + , uri: 'https://test.sparkpost.com/test' + , json: { + testingData: 'test data' + } + }; + + client.request(options, function(err, data) { + expect(data.body).to.not.be.a('string'); + expect(data.body).to.be.an('object'); + expect(data.body).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 deliever a PUT/UPDATE', function(done) { + var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') .put('/api/v1/put/test') @@ -310,14 +374,44 @@ describe('SparkPost Library', function() { done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .put('/test') + .reply(200, '{ "ok": true }'); + + var options = { + method: 'PUT' + , uri: 'https://test.sparkpost.com/test' + , json: { + testingData: 'test data' + } + }; + + client.request(options, function(err, data) { + expect(data.body).to.not.be.a('string'); + expect(data.body).to.be.an('object'); + expect(data.body).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 deliever a DELETE', function(done) { + var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') .delete('/api/v1/delete/test') @@ -341,5 +435,28 @@ describe('SparkPost Library', function() { done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .delete('/test') + .reply(200, '{ "ok": true }'); + + var options = { + method: 'DELETE' + , uri: 'https://test.sparkpost.com/test' + , json: { + testingData: 'test data' + } + }; + + client.request(options, function(err, data) { + expect(data.body).to.not.be.a('string'); + expect(data.body).to.be.an('object'); + expect(data.body).to.deep.equal({ok: true}); + + // finish async test + done(); + }); + }); }); }); From 9a735c51a90aa8a11f4cb8ab515a93b086b0e3ab Mon Sep 17 00:00:00 2001 From: "Aydrian J. Howard" Date: Tue, 22 Mar 2016 11:44:05 -0400 Subject: [PATCH 02/27] Fixed a couple misspellings --- test/spec/sparkpost.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 2a5cbc4..04ea662 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -349,7 +349,7 @@ describe('SparkPost Library', function() { client = new SparkPost(key, options); }); - it('should deliever a PUT/UPDATE', function(done) { + it('should deliver a PUT/UPDATE', function(done) { var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') @@ -410,7 +410,7 @@ describe('SparkPost Library', function() { client = new SparkPost(key, options); }); - it('should deliever a DELETE', function(done) { + it('should deliver a DELETE', function(done) { var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') From 876b6bf57267c796af3420fca411dff16d09864f Mon Sep 17 00:00:00 2001 From: Aydrian Date: Mon, 25 Apr 2016 13:50:40 -0400 Subject: [PATCH 03/27] Returns body.results or body as a response. Added debug support. (#112) * Now returning body.results or body as a response. Added debug support. * Updated documents and examples * Updating newly merged code * Updated debug flag doc in README.md --- README.md | 7 ++- docs/resources/inboundDomains.md | 2 +- docs/resources/messageEvents.md | 6 +- docs/resources/recipientLists.md | 2 +- docs/resources/relayWebhooks.md | 2 +- docs/resources/sendingDomains.md | 2 +- docs/resources/subaccounts.md | 2 +- docs/resources/suppressionList.md | 2 +- docs/resources/templates.md | 2 +- docs/resources/webhooks.md | 2 +- examples/baseObject/getDomainsList.js | 2 +- .../inboundDomains/create_inboundDomain.js | 4 +- .../inboundDomains/delete_inboundDomain.js | 4 +- examples/inboundDomains/find_inboundDomain.js | 4 +- .../inboundDomains/get_all_inboundDomains.js | 4 +- examples/messageEvents/all_messageEvents.js | 6 +- .../messageEvents/search_campaignClicks.js | 6 +- .../messageEvents/search_messageEvents.js | 6 +- .../recipientLists/create_recipientList.js | 6 +- .../recipientLists/delete_recipientList.js | 6 +- .../recipientLists/get_all_recipientLists.js | 6 +- examples/recipientLists/get_recipientList.js | 6 +- .../get_recipientList_with_recipients.js | 6 +- .../recipientLists/update_recipientList.js | 6 +- examples/relayWebhooks/create_relayWebhook.js | 4 +- examples/relayWebhooks/delete_relayWebhook.js | 4 +- examples/relayWebhooks/find_relayWebhook.js | 4 +- .../relayWebhooks/get_all_relayWebhooks.js | 4 +- examples/relayWebhooks/update_relayWebhook.js | 4 +- .../sendingDomains/create_sendingDomain.js | 6 +- .../sendingDomains/get_all_sendingDomains.js | 6 +- examples/sendingDomains/get_sendingDomain.js | 6 +- .../sendingDomains/update_sendingDomain.js | 6 +- .../verify_sendingDomain_default.js | 6 +- .../verify_sendingDomain_dkim_only.js | 6 +- .../verify_sendingDomain_spf_only.js | 6 +- examples/suppressionList/checkStatus.js | 6 +- examples/suppressionList/removeStatus.js | 6 +- .../suppressionList/search_suppressionList.js | 6 +- examples/suppressionList/upsert.js | 6 +- examples/suppressionList/upsert_bulk.js | 6 +- examples/templates/create_template.js | 6 +- examples/templates/delete_template.js | 6 +- examples/templates/get_all_templates.js | 6 +- examples/templates/get_draft_template.js | 6 +- examples/templates/get_template.js | 6 +- examples/templates/preview_template.js | 6 +- .../templates/update_published_template.js | 6 +- examples/templates/update_template.js | 6 +- .../transmissions/get_all_transmissions.js | 6 +- examples/transmissions/get_transmission.js | 6 +- .../get_transmissions_by_campaign.js | 6 +- .../get_transmissions_by_template.js | 6 +- examples/transmissions/mime_parts.js | 6 +- examples/transmissions/rfc822.js | 6 +- .../send_transmission_all_fields.js | 6 +- .../stored_recipients_inline_content.js | 6 +- .../stored_recipients_stored_content.js | 6 +- .../transmissions/stored_template_send.js | 4 +- examples/webhooks/create_webhook.js | 6 +- examples/webhooks/delete_webhook.js | 6 +- examples/webhooks/describe_webhook.js | 6 +- examples/webhooks/getBatchStatus.js | 6 +- examples/webhooks/getDocumentation.js | 6 +- examples/webhooks/getSamples.js | 6 +- examples/webhooks/get_all_webhooks.js | 6 +- examples/webhooks/update_webhook.js | 6 +- examples/webhooks/validate_webhook.js | 6 +- lib/sparkpost.js | 22 +++++-- test/spec/SendGridCompatibility/index.spec.js | 2 +- test/spec/sparkpost.spec.js | 61 +++++++++++-------- 71 files changed, 228 insertions(+), 210 deletions(-) diff --git a/README.md b/README.md index ad86d29..dc45c9c 100644 --- a/README.md +++ b/README.md @@ -45,11 +45,12 @@ npm install sparkpost * **request(options, callback)** * `options` - [see request modules options](https://github.com/mikeal/request#requestoptions-callback) * `options.uri` - can either be a full url or a path that is appended to `options.origin` used at initialization ([url.resolve](http://nodejs.org/api/url.html#url_url_resolve_from_to)) + * `options.debug` - setting to `true` includes full response from request client for debugging purposes * `callback` - executed after task is completed. **required** * standard `callback(err, data)` * `err` - any error that occurred - * `data.res` - full response from request client - * `data.body` - payload from response + * `data` - results from API call + * `data.debug` - full response from request client when `options.debug` is `true` * **get | post | put | delete(options, callback)** * `options` - see request options * `callback` - see request options @@ -97,7 +98,7 @@ client.get(options, function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/inboundDomains.md b/docs/resources/inboundDomains.md index 81175c5..7c5746f 100644 --- a/docs/resources/inboundDomains.md +++ b/docs/resources/inboundDomains.md @@ -34,7 +34,7 @@ client.inboundDomains.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/messageEvents.md b/docs/resources/messageEvents.md index b0d0892..6ef8bef 100644 --- a/docs/resources/messageEvents.md +++ b/docs/resources/messageEvents.md @@ -6,8 +6,8 @@ This library provides easy access to the [Message Events](https://www.sparkpost. * **search(params, callback)** Search for message events using the given parameters (NOTE: all params are optional): * `params.bounce_classes` - list of [bounce classes](https://support.sparkpost.com/customer/portal/articles/1929896) - * `params.campaign_ids` - campaign IDs - * `params.events` - event types + * `params.campaign_ids` - campaign IDs + * `params.events` - event types * `params.friendly_froms` - 'friendly' from addressess * `params.from` - time lower bound (see below for date/time format details) * `params.message_ids` - message IDs @@ -52,7 +52,7 @@ client.messageEvents.search(searchParams, function(err, res) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/recipientLists.md b/docs/resources/recipientLists.md index 5fa4ca6..32a6812 100644 --- a/docs/resources/recipientLists.md +++ b/docs/resources/recipientLists.md @@ -42,7 +42,7 @@ client.recipientLists.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/relayWebhooks.md b/docs/resources/relayWebhooks.md index 2d64a47..2fc7f95 100644 --- a/docs/resources/relayWebhooks.md +++ b/docs/resources/relayWebhooks.md @@ -47,7 +47,7 @@ client.relayWebhooks.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/sendingDomains.md b/docs/resources/sendingDomains.md index 0c11777..a5199c8 100644 --- a/docs/resources/sendingDomains.md +++ b/docs/resources/sendingDomains.md @@ -43,7 +43,7 @@ client.sendingDomains.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/subaccounts.md b/docs/resources/subaccounts.md index d948692..70a7f20 100644 --- a/docs/resources/subaccounts.md +++ b/docs/resources/subaccounts.md @@ -41,6 +41,6 @@ client.subaccounts.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/suppressionList.md b/docs/resources/suppressionList.md index 388a543..7fdb594 100644 --- a/docs/resources/suppressionList.md +++ b/docs/resources/suppressionList.md @@ -37,7 +37,7 @@ client.suppressionList.search(parameters, function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/templates.md b/docs/resources/templates.md index fffab0d..df905da 100644 --- a/docs/resources/templates.md +++ b/docs/resources/templates.md @@ -41,7 +41,7 @@ client.templates.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/docs/resources/webhooks.md b/docs/resources/webhooks.md index 8a752ba..1a27242 100644 --- a/docs/resources/webhooks.md +++ b/docs/resources/webhooks.md @@ -57,7 +57,7 @@ client.webhooks.all(function(err, data) { return; } - console.log(data.body); + console.log(data); }); ``` diff --git a/examples/baseObject/getDomainsList.js b/examples/baseObject/getDomainsList.js index f3c3ea8..a025fd8 100644 --- a/examples/baseObject/getDomainsList.js +++ b/examples/baseObject/getDomainsList.js @@ -13,5 +13,5 @@ client.get(options, function(err, data) { return; } - console.log(data.body); + console.log(data); }); diff --git a/examples/inboundDomains/create_inboundDomain.js b/examples/inboundDomains/create_inboundDomain.js index 507f2a5..f803134 100644 --- a/examples/inboundDomains/create_inboundDomain.js +++ b/examples/inboundDomains/create_inboundDomain.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.inboundDomains.create('example1.com', function(err, res) { +client.inboundDomains.create('example1.com', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/inboundDomains/delete_inboundDomain.js b/examples/inboundDomains/delete_inboundDomain.js index 29c6936..d3056f5 100644 --- a/examples/inboundDomains/delete_inboundDomain.js +++ b/examples/inboundDomains/delete_inboundDomain.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.inboundDomains.delete('example1.com', function(err, res) { +client.inboundDomains.delete('example1.com', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/inboundDomains/find_inboundDomain.js b/examples/inboundDomains/find_inboundDomain.js index 76b4aaf..9b83178 100644 --- a/examples/inboundDomains/find_inboundDomain.js +++ b/examples/inboundDomains/find_inboundDomain.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.inboundDomains.find('example1.com', function(err, res) { +client.inboundDomains.find('example1.com', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/inboundDomains/get_all_inboundDomains.js b/examples/inboundDomains/get_all_inboundDomains.js index cc0f4ed..59bcf34 100644 --- a/examples/inboundDomains/get_all_inboundDomains.js +++ b/examples/inboundDomains/get_all_inboundDomains.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.inboundDomains.all(function(err, res) { +client.inboundDomains.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/messageEvents/all_messageEvents.js b/examples/messageEvents/all_messageEvents.js index 5ad4ff3..113158c 100644 --- a/examples/messageEvents/all_messageEvents.js +++ b/examples/messageEvents/all_messageEvents.js @@ -4,12 +4,12 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.messageEvents.search({}, function(err, res) { +client.messageEvents.search({}, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/messageEvents/search_campaignClicks.js b/examples/messageEvents/search_campaignClicks.js index 82b9e79..49b74bd 100644 --- a/examples/messageEvents/search_campaignClicks.js +++ b/examples/messageEvents/search_campaignClicks.js @@ -8,12 +8,12 @@ var key = 'YOURAPIKEY' campaign_ids: 'monday_mailshot' }; -client.messageEvents.search(searchParams, function(err, res) { +client.messageEvents.search(searchParams, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/messageEvents/search_messageEvents.js b/examples/messageEvents/search_messageEvents.js index c446367..9b2250a 100644 --- a/examples/messageEvents/search_messageEvents.js +++ b/examples/messageEvents/search_messageEvents.js @@ -12,12 +12,12 @@ var key = 'YOURAPIKEY' bounce_classes: [10] }; -client.messageEvents.search(searchParams, function(err, res) { +client.messageEvents.search(searchParams, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/recipientLists/create_recipientList.js b/examples/recipientLists/create_recipientList.js index 8f268f0..0ea932b 100644 --- a/examples/recipientLists/create_recipientList.js +++ b/examples/recipientLists/create_recipientList.js @@ -25,11 +25,11 @@ var key = 'YOURAPIKEY' ] }; -client.recipientLists.create(options, function(err, res) { +client.recipientLists.create(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/recipientLists/delete_recipientList.js b/examples/recipientLists/delete_recipientList.js index afabc46..97bc883 100644 --- a/examples/recipientLists/delete_recipientList.js +++ b/examples/recipientLists/delete_recipientList.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.recipientLists['delete']('UNIQUE_TEST_ID', function(err, res) { +client.recipientLists['delete']('UNIQUE_TEST_ID', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/recipientLists/get_all_recipientLists.js b/examples/recipientLists/get_all_recipientLists.js index 6f24c7d..b0ea723 100644 --- a/examples/recipientLists/get_all_recipientLists.js +++ b/examples/recipientLists/get_all_recipientLists.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.recipientLists.all(function(err, res) { +client.recipientLists.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/recipientLists/get_recipientList.js b/examples/recipientLists/get_recipientList.js index a4b1e82..3180c9b 100644 --- a/examples/recipientLists/get_recipientList.js +++ b/examples/recipientLists/get_recipientList.js @@ -7,11 +7,11 @@ var key = 'YOURAPIKEY' id: 'UNIQUE_TEST_ID' }; -client.recipientLists.find(options, function(err, res) { +client.recipientLists.find(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/recipientLists/get_recipientList_with_recipients.js b/examples/recipientLists/get_recipientList_with_recipients.js index 15d2415..12007f7 100644 --- a/examples/recipientLists/get_recipientList_with_recipients.js +++ b/examples/recipientLists/get_recipientList_with_recipients.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , show_recipients: true }; -client.recipientLists.find(options, function(err, res) { +client.recipientLists.find(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/recipientLists/update_recipientList.js b/examples/recipientLists/update_recipientList.js index 9e4087e..5814ed6 100644 --- a/examples/recipientLists/update_recipientList.js +++ b/examples/recipientLists/update_recipientList.js @@ -25,11 +25,11 @@ var key = 'YOURAPIKEY' ] }; -client.recipientLists.update(options, function(err, res) { +client.recipientLists.update(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/relayWebhooks/create_relayWebhook.js b/examples/relayWebhooks/create_relayWebhook.js index 0475de2..0544e0d 100644 --- a/examples/relayWebhooks/create_relayWebhook.js +++ b/examples/relayWebhooks/create_relayWebhook.js @@ -9,11 +9,11 @@ var key = 'YOURAPIKEY' , domain: 'inbound.example.com' }; -client.relayWebhooks.create(options, function(err, res) { +client.relayWebhooks.create(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/relayWebhooks/delete_relayWebhook.js b/examples/relayWebhooks/delete_relayWebhook.js index e401783..beec64d 100644 --- a/examples/relayWebhooks/delete_relayWebhook.js +++ b/examples/relayWebhooks/delete_relayWebhook.js @@ -5,11 +5,11 @@ var key = 'YOURAPIKEY' , client = new SparkPost(key) , relayWebhookId = '123456789'; -client.relayWebhooks.delete(relayWebhookId, function(err, res) { +client.relayWebhooks.delete(relayWebhookId, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/relayWebhooks/find_relayWebhook.js b/examples/relayWebhooks/find_relayWebhook.js index 272ca44..b42eb3e 100644 --- a/examples/relayWebhooks/find_relayWebhook.js +++ b/examples/relayWebhooks/find_relayWebhook.js @@ -5,11 +5,11 @@ var key = 'YOURAPIKEY' , client = new SparkPost(key) , relayWebhookId = '123456789'; -client.relayWebhooks.find(relayWebhookId, function(err, res) { +client.relayWebhooks.find(relayWebhookId, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/relayWebhooks/get_all_relayWebhooks.js b/examples/relayWebhooks/get_all_relayWebhooks.js index 864f9e3..5729fe3 100644 --- a/examples/relayWebhooks/get_all_relayWebhooks.js +++ b/examples/relayWebhooks/get_all_relayWebhooks.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.relayWebhooks.all(function(err, res) { +client.relayWebhooks.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/relayWebhooks/update_relayWebhook.js b/examples/relayWebhooks/update_relayWebhook.js index 302e5eb..ed3ef7e 100644 --- a/examples/relayWebhooks/update_relayWebhook.js +++ b/examples/relayWebhooks/update_relayWebhook.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , target: 'http://client.test.com/test-webhook' }; -client.relayWebhooks.update(options, function(err, res) { +client.relayWebhooks.update(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/create_sendingDomain.js b/examples/sendingDomains/create_sendingDomain.js index ed7c207..bcb2c86 100644 --- a/examples/sendingDomains/create_sendingDomain.js +++ b/examples/sendingDomains/create_sendingDomain.js @@ -14,11 +14,11 @@ var domain = { } }; -client.sendingDomains.create(domain, function(err, res) { +client.sendingDomains.create(domain, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/get_all_sendingDomains.js b/examples/sendingDomains/get_all_sendingDomains.js index ef4086e..c9d9e6b 100644 --- a/examples/sendingDomains/get_all_sendingDomains.js +++ b/examples/sendingDomains/get_all_sendingDomains.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.sendingDomains.all(function(err, res) { +client.sendingDomains.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/get_sendingDomain.js b/examples/sendingDomains/get_sendingDomain.js index 70e4df8..945e153 100644 --- a/examples/sendingDomains/get_sendingDomain.js +++ b/examples/sendingDomains/get_sendingDomain.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.sendingDomains.find('example1.com', function(err, res) { +client.sendingDomains.find('example1.com', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/update_sendingDomain.js b/examples/sendingDomains/update_sendingDomain.js index 9abe145..bb29ce8 100644 --- a/examples/sendingDomains/update_sendingDomain.js +++ b/examples/sendingDomains/update_sendingDomain.js @@ -14,11 +14,11 @@ var key = 'YOURAPIKEY' } }; -client.sendingDomains.update(domain, function(err, res) { +client.sendingDomains.update(domain, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/verify_sendingDomain_default.js b/examples/sendingDomains/verify_sendingDomain_default.js index 059722d..9184b51 100644 --- a/examples/sendingDomains/verify_sendingDomain_default.js +++ b/examples/sendingDomains/verify_sendingDomain_default.js @@ -7,11 +7,11 @@ var key = 'YOURAPIKEY' domain: 'example1.com' }; -client.sendingDomains.verify(options, function(err, res) { +client.sendingDomains.verify(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/verify_sendingDomain_dkim_only.js b/examples/sendingDomains/verify_sendingDomain_dkim_only.js index 35bfb7f..36328ab 100644 --- a/examples/sendingDomains/verify_sendingDomain_dkim_only.js +++ b/examples/sendingDomains/verify_sendingDomain_dkim_only.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , verifySPF: false }; -client.sendingDomains.verify(options, function(err, res) { +client.sendingDomains.verify(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/sendingDomains/verify_sendingDomain_spf_only.js b/examples/sendingDomains/verify_sendingDomain_spf_only.js index f640710..245c501 100644 --- a/examples/sendingDomains/verify_sendingDomain_spf_only.js +++ b/examples/sendingDomains/verify_sendingDomain_spf_only.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , verifyDKIM: false }; -client.sendingDomains.verify(options, function(err, res) { +client.sendingDomains.verify(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/suppressionList/checkStatus.js b/examples/suppressionList/checkStatus.js index 888dc01..8ff3fdd 100644 --- a/examples/suppressionList/checkStatus.js +++ b/examples/suppressionList/checkStatus.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.suppressionList.checkStatus('test@test.com', function(err, res) { +client.suppressionList.checkStatus('test@test.com', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/suppressionList/removeStatus.js b/examples/suppressionList/removeStatus.js index 75881f8..d6862a0 100644 --- a/examples/suppressionList/removeStatus.js +++ b/examples/suppressionList/removeStatus.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.suppressionList.removeStatus('test@test.com', function(err, res) { +client.suppressionList.removeStatus('test@test.com', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/suppressionList/search_suppressionList.js b/examples/suppressionList/search_suppressionList.js index 4836870..8e1ed4c 100644 --- a/examples/suppressionList/search_suppressionList.js +++ b/examples/suppressionList/search_suppressionList.js @@ -9,11 +9,11 @@ var key = 'YOURAPIKEY' , limit: 5 }; -client.suppressionList.search(parameters, function(err, res) { +client.suppressionList.search(parameters, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/suppressionList/upsert.js b/examples/suppressionList/upsert.js index bb7ab8b..6c7e7bc 100644 --- a/examples/suppressionList/upsert.js +++ b/examples/suppressionList/upsert.js @@ -10,11 +10,11 @@ var key = 'YOURAPIKEY' , description: 'Test description' }; -client.suppressionList.upsert(recipient, function(err, res) { +client.suppressionList.upsert(recipient, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/suppressionList/upsert_bulk.js b/examples/suppressionList/upsert_bulk.js index 98171a1..29f23b9 100644 --- a/examples/suppressionList/upsert_bulk.js +++ b/examples/suppressionList/upsert_bulk.js @@ -24,11 +24,11 @@ var key = 'YOURAPIKEY' } ]; -client.suppressionList.upsert(recipients, function(err, res) { +client.suppressionList.upsert(recipients, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/create_template.js b/examples/templates/create_template.js index a6f6ca4..a6cb7fc 100644 --- a/examples/templates/create_template.js +++ b/examples/templates/create_template.js @@ -15,11 +15,11 @@ var key = 'YOURAPIKEY' } }; -client.templates.create(options, function(err, res) { +client.templates.create(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/delete_template.js b/examples/templates/delete_template.js index a780bba..93ebaa0 100644 --- a/examples/templates/delete_template.js +++ b/examples/templates/delete_template.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.templates['delete']('TEST_ID', function(err, res) { +client.templates['delete']('TEST_ID', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/get_all_templates.js b/examples/templates/get_all_templates.js index 8f3f309..e079062 100644 --- a/examples/templates/get_all_templates.js +++ b/examples/templates/get_all_templates.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.templates.all(function(err, res) { +client.templates.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/get_draft_template.js b/examples/templates/get_draft_template.js index 87a1c34..d4f6b7c 100644 --- a/examples/templates/get_draft_template.js +++ b/examples/templates/get_draft_template.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , draft: true }; -client.templates.find(options, function(err, res) { +client.templates.find(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/get_template.js b/examples/templates/get_template.js index e4a41d4..8a64a28 100644 --- a/examples/templates/get_template.js +++ b/examples/templates/get_template.js @@ -7,11 +7,11 @@ var key = 'YOURAPIKEY' id: 'TEST_ID' }; -client.templates.find(options, function(err, res) { +client.templates.find(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/preview_template.js b/examples/templates/preview_template.js index 261c314..b3b62ba 100644 --- a/examples/templates/preview_template.js +++ b/examples/templates/preview_template.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , data: {} }; -client.templates.preview(options, function(err, res) { +client.templates.preview(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/update_published_template.js b/examples/templates/update_published_template.js index ca6a411..3cbc1a8 100644 --- a/examples/templates/update_published_template.js +++ b/examples/templates/update_published_template.js @@ -15,11 +15,11 @@ var key = 'YOURAPIKEY' , update_published: true }; -client.templates.update(options, function(err, res) { +client.templates.update(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/templates/update_template.js b/examples/templates/update_template.js index ebf570c..d3973c8 100644 --- a/examples/templates/update_template.js +++ b/examples/templates/update_template.js @@ -14,11 +14,11 @@ var key = 'YOURAPIKEY' } }; -client.templates.update(options, function(err, res) { +client.templates.update(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/get_all_transmissions.js b/examples/transmissions/get_all_transmissions.js index cf56dbf..f5b735d 100644 --- a/examples/transmissions/get_all_transmissions.js +++ b/examples/transmissions/get_all_transmissions.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.transmissions.all(function(err, res) { +client.transmissions.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/get_transmission.js b/examples/transmissions/get_transmission.js index 2f75daa..212939d 100644 --- a/examples/transmissions/get_transmission.js +++ b/examples/transmissions/get_transmission.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.transmissions.find('YOUR-TRANSMISSION-KEY', function(err, res) { +client.transmissions.find('YOUR-TRANSMISSION-KEY', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/get_transmissions_by_campaign.js b/examples/transmissions/get_transmissions_by_campaign.js index a1bc054..75030da 100644 --- a/examples/transmissions/get_transmissions_by_campaign.js +++ b/examples/transmissions/get_transmissions_by_campaign.js @@ -7,11 +7,11 @@ var key = 'YOURAPIKEY' campaign_id: 'my_campaign' }; -client.transmissions.all(options, function(err, res) { +client.transmissions.all(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/get_transmissions_by_template.js b/examples/transmissions/get_transmissions_by_template.js index ed58259..ca28ce7 100644 --- a/examples/transmissions/get_transmissions_by_template.js +++ b/examples/transmissions/get_transmissions_by_template.js @@ -7,11 +7,11 @@ var key = 'YOURAPIKEY' template_id: 'my_template' }; -client.transmissions.all(options, function(err, res) { +client.transmissions.all(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/mime_parts.js b/examples/transmissions/mime_parts.js index dd949bf..7050e54 100644 --- a/examples/transmissions/mime_parts.js +++ b/examples/transmissions/mime_parts.js @@ -20,11 +20,11 @@ var reqObj = { } }; -client.transmissions.send(reqObj, function(err, res) { +client.transmissions.send(reqObj, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/rfc822.js b/examples/transmissions/rfc822.js index 56ce9e5..52b6b07 100644 --- a/examples/transmissions/rfc822.js +++ b/examples/transmissions/rfc822.js @@ -13,11 +13,11 @@ var reqObj = { } }; -client.transmissions.send(reqObj, function(err, res) { +client.transmissions.send(reqObj, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/send_transmission_all_fields.js b/examples/transmissions/send_transmission_all_fields.js index a41ccba..637c9b5 100644 --- a/examples/transmissions/send_transmission_all_fields.js +++ b/examples/transmissions/send_transmission_all_fields.js @@ -55,11 +55,11 @@ var reqOpts = { } }; -client.transmissions.send(reqOpts, function(err, res) { +client.transmissions.send(reqOpts, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log("Congrats you can use our SDK!"); + console.log(data); + console.log("Congrats you can use our client library!"); } }); diff --git a/examples/transmissions/stored_recipients_inline_content.js b/examples/transmissions/stored_recipients_inline_content.js index a087db5..eb5aee6 100644 --- a/examples/transmissions/stored_recipients_inline_content.js +++ b/examples/transmissions/stored_recipients_inline_content.js @@ -18,11 +18,11 @@ var reqObj = { } }; -client.transmissions.send(reqObj, function(err, res) { +client.transmissions.send(reqObj, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/stored_recipients_stored_content.js b/examples/transmissions/stored_recipients_stored_content.js index 2609013..3722545 100644 --- a/examples/transmissions/stored_recipients_stored_content.js +++ b/examples/transmissions/stored_recipients_stored_content.js @@ -17,11 +17,11 @@ var reqOpts = { } }; -client.transmissions.send(reqOpts, function(err, res) { +client.transmissions.send(reqOpts, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/stored_template_send.js b/examples/transmissions/stored_template_send.js index 5189262..aa4c2d3 100644 --- a/examples/transmissions/stored_template_send.js +++ b/examples/transmissions/stored_template_send.js @@ -15,11 +15,11 @@ var reqOpts = { } }; -client.transmissions.send(reqOpts, function(err, res) { +client.transmissions.send(reqOpts, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('What up my glib globs! SparkPost!'); } }); diff --git a/examples/webhooks/create_webhook.js b/examples/webhooks/create_webhook.js index 1d1b19d..f2a9ef9 100644 --- a/examples/webhooks/create_webhook.js +++ b/examples/webhooks/create_webhook.js @@ -15,11 +15,11 @@ var key = 'YOURAPIKEY' ] }; -client.webhooks.create(webhook, function(err, res) { +client.webhooks.create(webhook, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/delete_webhook.js b/examples/webhooks/delete_webhook.js index 95f75cf..e0ae3ae 100644 --- a/examples/webhooks/delete_webhook.js +++ b/examples/webhooks/delete_webhook.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.webhooks['delete']('TEST_WEBHOOK_UUID', function(err, res) { +client.webhooks['delete']('TEST_WEBHOOK_UUID', function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/describe_webhook.js b/examples/webhooks/describe_webhook.js index 99e9020..9fc6088 100644 --- a/examples/webhooks/describe_webhook.js +++ b/examples/webhooks/describe_webhook.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , timezone: 'America/New_York' }; -client.webhooks.describe(options, function(err, res) { +client.webhooks.describe(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/getBatchStatus.js b/examples/webhooks/getBatchStatus.js index d527cc3..b855967 100644 --- a/examples/webhooks/getBatchStatus.js +++ b/examples/webhooks/getBatchStatus.js @@ -8,11 +8,11 @@ var key = 'YOURAPIKEY' , limit: 1000 }; -client.webhooks.getBatchStatus(options, function(err, res) { +client.webhooks.getBatchStatus(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/getDocumentation.js b/examples/webhooks/getDocumentation.js index d9acc9f..5a7dfd0 100644 --- a/examples/webhooks/getDocumentation.js +++ b/examples/webhooks/getDocumentation.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.webhooks.getDocumentation(function(err, res) { +client.webhooks.getDocumentation(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/getSamples.js b/examples/webhooks/getSamples.js index 6930d77..c754330 100644 --- a/examples/webhooks/getSamples.js +++ b/examples/webhooks/getSamples.js @@ -7,11 +7,11 @@ var key = 'YOURAPIKEY' events: 'bounce' }; -client.webhooks.getSamples(options, function(err, res) { +client.webhooks.getSamples(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/get_all_webhooks.js b/examples/webhooks/get_all_webhooks.js index 3f36053..c5f19dd 100644 --- a/examples/webhooks/get_all_webhooks.js +++ b/examples/webhooks/get_all_webhooks.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.webhooks.all(function(err, res) { +client.webhooks.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/update_webhook.js b/examples/webhooks/update_webhook.js index 05284c5..781e8a0 100644 --- a/examples/webhooks/update_webhook.js +++ b/examples/webhooks/update_webhook.js @@ -12,11 +12,11 @@ var key = 'YOURAPIKEY' ] }; -client.webhooks.update(webhook, function(err, res) { +client.webhooks.update(webhook, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/webhooks/validate_webhook.js b/examples/webhooks/validate_webhook.js index 5b885ba..8576d8f 100644 --- a/examples/webhooks/validate_webhook.js +++ b/examples/webhooks/validate_webhook.js @@ -10,11 +10,11 @@ var key = 'YOURAPIKEY' } }; -client.webhooks.validate(options, function(err, res) { +client.webhooks.validate(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log(data); + console.log('Congrats you can use our client library!'); } }); diff --git a/lib/sparkpost.js b/lib/sparkpost.js index d4bd02c..7745169 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -32,6 +32,16 @@ var handleOptions = function(apiKey, options) { return options; }; +var createSparkPostError = function(res, body) { + body = body || {}; + var err = new Error(res.statusMessage); + err.name = 'SparkPostError'; + err.errors = body.errors; + err.statusCode = res.statusCode; + + return err; +}; + var SparkPost = function(apiKey, options) { options = handleOptions(apiKey, options); @@ -101,14 +111,14 @@ SparkPost.prototype.request = function( options, callback ) { 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; + err = createSparkPostError(res, body); return callback(err, res); } else { - return callback(null, res); + var response = body.results || body; + if(options.debug) { + response.debug = res; + } + return callback(null, response); } }); }; diff --git a/test/spec/SendGridCompatibility/index.spec.js b/test/spec/SendGridCompatibility/index.spec.js index 52bd367..e4bc46d 100644 --- a/test/spec/SendGridCompatibility/index.spec.js +++ b/test/spec/SendGridCompatibility/index.spec.js @@ -128,7 +128,7 @@ describe('SendGrid Compatibility', function() { it('should respond when the test succeeds', function(done) { sendgrid.send({}, function(err, res) { - expect(res.body.ok).to.be.true; + expect(res.ok).to.be.true; expect(err).to.equal(null); done(); }); diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 68a1e25..99ed1eb 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -94,11 +94,12 @@ describe('SparkPost Library', function() { var options = { method: 'GET' , uri: 'get/test' + , 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(); @@ -179,10 +180,11 @@ describe('SparkPost Library', function() { var options = { method: 'GET' , uri: 'https://test.sparkpost.com/test' + , 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 +198,10 @@ describe('SparkPost Library', function() { , options = { method: 'GET' , uri: 'https://test.sparkpost.com/test' - }; + , 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 +217,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 +231,20 @@ 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 + , 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(); @@ -266,12 +270,12 @@ describe('SparkPost Library', function() { .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(); @@ -289,9 +293,9 @@ describe('SparkPost Library', function() { }; client.request(options, function(err, data) { - expect(data.body).to.not.be.a('string'); - expect(data.body).to.be.an('object'); - expect(data.body).to.deep.equal({ok: true}); + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); // finish async test done(); @@ -322,6 +326,7 @@ describe('SparkPost Library', function() { , json: { testingData: 'test data' } + , debug: true }; client.post(reqOptions, function(err, data) { @@ -329,7 +334,7 @@ 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(); @@ -350,9 +355,9 @@ describe('SparkPost Library', function() { }; client.request(options, function(err, data) { - expect(data.body).to.not.be.a('string'); - expect(data.body).to.be.an('object'); - expect(data.body).to.deep.equal({ok: true}); + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); // finish async test done(); @@ -383,6 +388,7 @@ describe('SparkPost Library', function() { , json: { testingData: 'test data' } + , debug: true }; client.put(reqOptions, function(err, data) { @@ -390,7 +396,7 @@ 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(); @@ -411,9 +417,9 @@ describe('SparkPost Library', function() { }; client.request(options, function(err, data) { - expect(data.body).to.not.be.a('string'); - expect(data.body).to.be.an('object'); - expect(data.body).to.deep.equal({ok: true}); + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); // finish async test done(); @@ -444,6 +450,7 @@ describe('SparkPost Library', function() { , json: { testingData: 'test data' } + , debug: true }; client.delete(reqOptions, function(err, data) { @@ -451,7 +458,7 @@ 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(); @@ -472,9 +479,9 @@ describe('SparkPost Library', function() { }; client.request(options, function(err, data) { - expect(data.body).to.not.be.a('string'); - expect(data.body).to.be.an('object'); - expect(data.body).to.deep.equal({ok: true}); + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); // finish async test done(); From 0564e2560eaa02384ac51d3edb421602ca3910db Mon Sep 17 00:00:00 2001 From: "Aydrian J. Howard" Date: Thu, 18 Aug 2016 11:19:43 -0400 Subject: [PATCH 04/27] clean up from 1.x merge --- docs/resources/transmissions.md | 2 +- examples/subaccounts/create_subaccount.js | 4 ++-- examples/subaccounts/get_all_subaccounts.js | 4 ++-- examples/subaccounts/get_subaccount.js | 4 ++-- examples/subaccounts/update_subaccount.js | 4 ++-- examples/suppressionList/upsert.js | 2 +- examples/transmissions/send_transmission_with_bcc.js | 4 ++-- examples/transmissions/send_transmission_with_cc.js | 4 ++-- 8 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/resources/transmissions.md b/docs/resources/transmissions.md index 3547ea7..b899f95 100644 --- a/docs/resources/transmissions.md +++ b/docs/resources/transmissions.md @@ -42,7 +42,7 @@ var reqObj = { } }; -client.transmissions.send(reqObj, function(err, res) { +client.transmissions.send(reqObj, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/subaccounts/create_subaccount.js b/examples/subaccounts/create_subaccount.js index ac6b37e..e67b2b6 100644 --- a/examples/subaccounts/create_subaccount.js +++ b/examples/subaccounts/create_subaccount.js @@ -12,11 +12,11 @@ var key = 'YOURAPIKEY' ] }; -client.subaccounts.create(options, function(err, res) { +client.subaccounts.create(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/subaccounts/get_all_subaccounts.js b/examples/subaccounts/get_all_subaccounts.js index ea0cfa6..e9c6078 100644 --- a/examples/subaccounts/get_all_subaccounts.js +++ b/examples/subaccounts/get_all_subaccounts.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.subaccounts.all(function(err, res) { +client.subaccounts.all(function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/subaccounts/get_subaccount.js b/examples/subaccounts/get_subaccount.js index c207d8a..47bf82e 100644 --- a/examples/subaccounts/get_subaccount.js +++ b/examples/subaccounts/get_subaccount.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.subaccounts.find(123, function(err, res) { +client.subaccounts.find(123, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/subaccounts/update_subaccount.js b/examples/subaccounts/update_subaccount.js index 02e16c3..3123982 100644 --- a/examples/subaccounts/update_subaccount.js +++ b/examples/subaccounts/update_subaccount.js @@ -9,11 +9,11 @@ var key = 'YOURAPIKEY' , status: 'suspended' }; -client.subaccounts.update(options, function(err, res) { +client.subaccounts.update(options, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log('Congrats you can use our client library!'); } }); diff --git a/examples/suppressionList/upsert.js b/examples/suppressionList/upsert.js index 3233aba..29f23b9 100644 --- a/examples/suppressionList/upsert.js +++ b/examples/suppressionList/upsert.js @@ -24,7 +24,7 @@ var key = 'YOURAPIKEY' } ]; -client.suppressionList.upsert(recipient, function(err, data) { +client.suppressionList.upsert(recipients, function(err, data) { if (err) { console.log(err); } else { diff --git a/examples/transmissions/send_transmission_with_bcc.js b/examples/transmissions/send_transmission_with_bcc.js index 1b99388..d91fc32 100644 --- a/examples/transmissions/send_transmission_with_bcc.js +++ b/examples/transmissions/send_transmission_with_bcc.js @@ -38,11 +38,11 @@ var reqOpts = { } }; -client.transmissions.send(reqOpts, function(err, res) { +client.transmissions.send(reqOpts, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); 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 index 3485b01..5813c89 100644 --- a/examples/transmissions/send_transmission_with_cc.js +++ b/examples/transmissions/send_transmission_with_cc.js @@ -42,11 +42,11 @@ var reqOpts = { } }; -client.transmissions.send(reqOpts, function(err, res) { +client.transmissions.send(reqOpts, function(err, data) { if (err) { console.log(err); } else { - console.log(res.body); + console.log(data); console.log("Congrats! You sent an email with cc using SparkPost!"); } }); From 23fdf266c750ea063b3a2dcac5c839f4c6941ccc Mon Sep 17 00:00:00 2001 From: Aydrian Date: Mon, 22 Aug 2016 11:06:01 -0400 Subject: [PATCH 05/27] Implement promise support (#154) * added promise support to base object * updated sendingDomains for promise support * updated inboundDomains for promise support * updated messageEvents for promise support * updated recipientLists for promise support * updated relayWebhooks for promise support * updated subaccounts for promise support * updated suppressionList for promise support * updated templates for promise support * updated transmissions for promise support * updated webhooks for promise support * Replaced bluebird with native promise support for PR #154 * removed dependency for bluebird * replaced bluebird on spec tests --- .jshintrc | 1 + lib/Promise.js | 31 ++++++++++++++ lib/inboundDomains.js | 21 +++++----- lib/messageEvents.js | 2 +- lib/recipientLists.js | 47 ++++++++++----------- lib/relayWebhooks.js | 35 +++++++--------- lib/sendingDomains.js | 35 +++++++--------- lib/sparkpost.js | 40 ++++++++++-------- lib/subaccounts.js | 27 ++++++------ lib/suppressionList.js | 19 ++++----- lib/templates.js | 56 ++++++++++++------------- lib/transmissions.js | 14 +++---- lib/webhooks.js | 70 ++++++++++++++----------------- package.json | 4 +- test/spec/inboundDomains.spec.js | 11 ++--- test/spec/messageEvents.spec.js | 8 ++-- test/spec/recipientLists.spec.js | 12 +++--- test/spec/relayWebhooks.spec.js | 12 +++--- test/spec/sendingDomains.spec.js | 20 +++++---- test/spec/sparkpost.spec.js | 3 -- test/spec/subaccounts.spec.js | 10 +++-- test/spec/suppressionList.spec.js | 12 +++--- test/spec/templates.spec.js | 12 +++--- test/spec/transmissions.spec.js | 8 ++-- test/spec/webhooks.spec.js | 12 +++--- 25 files changed, 273 insertions(+), 249 deletions(-) create mode 100644 lib/Promise.js diff --git a/.jshintrc b/.jshintrc index 2d96cd9..51bd36f 100644 --- a/.jshintrc +++ b/.jshintrc @@ -1,6 +1,7 @@ { "node" : true, "es3" : false, + "esnext" : true, "strict" : true, "curly" : true, "eqeqeq" : true, 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/inboundDomains.js b/lib/inboundDomains.js index 56e27c3..b9d4937 100644 --- a/lib/inboundDomains.js +++ b/lib/inboundDomains.js @@ -1,6 +1,8 @@ 'use strict'; -var api = 'inbound-domains'; +var api = 'inbound-domains' + /* global -Promise */ + , Promise = require('./Promise'); module.exports = function(client) { var inboundDomains = { @@ -8,7 +10,7 @@ module.exports = function(client) { var options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, find: function(domain, callback) { if(typeof domain === 'function') { @@ -17,14 +19,13 @@ module.exports = function(client) { } if(!domain) { - callback(new Error('domain is required')); - return; + return Promise.reject(new Error('domain is required')).asCallback(callback); } var options = { uri: api + '/' + domain }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, create: function(domain, callback) { if(typeof domain === 'function') { @@ -33,8 +34,7 @@ module.exports = function(client) { } if(!domain) { - callback(new Error('domain is required')); - return; + return Promise.reject(new Error('domain is required')).asCallback(callback); } var options = { @@ -43,7 +43,7 @@ module.exports = function(client) { domain: domain } }; - client.post(options, callback); + return client.post(options, callback).asCallback(callback); }, delete: function(domain, callback) { if (typeof domain === 'function') { @@ -52,14 +52,13 @@ module.exports = function(client) { } if (!domain) { - callback(new Error('domain is required')); - return; + return Promise.reject(new Error('domain is required')).asCallback(callback); } var options = { uri: api + '/' + domain }; - client.delete(options, callback); + return client.delete(options).asCallback(callback); } }; diff --git a/lib/messageEvents.js b/lib/messageEvents.js index e46f763..93cd40e 100644 --- a/lib/messageEvents.js +++ b/lib/messageEvents.js @@ -31,7 +31,7 @@ module.exports = function (client) { 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..4904822 100644 --- a/lib/recipientLists.js +++ b/lib/recipientLists.js @@ -1,6 +1,8 @@ 'use strict'; var api = 'recipient-lists' + /* global -Promise */ + , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); module.exports = function(client) { @@ -9,14 +11,13 @@ module.exports = function(client) { var reqOpts = { uri: api }; - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, find: function(options, callback) { options = options || {}; if(!options.id) { - callback(new Error('id is required')); - return; + return Promise.reject(new Error('id is required')).asCallback(callback); } var reqOpts = { @@ -28,14 +29,13 @@ module.exports = function(client) { reqOpts.qs.show_recipients = options.show_recipients; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, create: function(options, callback) { options = options || {}; if(!options.recipients) { - callback(new Error('recipients list is required')); - return; + return Promise.reject(new Error('recipients list is required')).asCallback(callback); } var reqOpts = { @@ -50,14 +50,13 @@ module.exports = function(client) { reqOpts.json = toApiFormat(options); - 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; + return Promise.reject(new Error('recipients list id is required')).asCallback(callback); } var reqOpts = { @@ -72,25 +71,23 @@ module.exports = function(client) { reqOpts.json = toApiFormat(options); - client.put(reqOpts, callback); - } - }; + return client.put(reqOpts, callback).asCallback(callback); + }, + delete: function(id, callback) { + if (typeof id === 'function') { + callback = id; + id = null; + } - recipientLists['delete'] = function(id, callback) { - if (typeof id === 'function') { - callback = id; - id = null; - } + if (!id) { + return Promise.reject(new Error('id is required')).asCallback(callback); + } - if (!id) { - callback(new Error('id is required')); - return; + var reqOpts = { + uri: api + '/' + id + }; + return client.delete(reqOpts).asCallback(callback); } - - var reqOpts = { - uri: api + '/' + id - }; - client['delete'](reqOpts, callback); }; return recipientLists; diff --git a/lib/relayWebhooks.js b/lib/relayWebhooks.js index dc22bce..b825286 100644 --- a/lib/relayWebhooks.js +++ b/lib/relayWebhooks.js @@ -1,6 +1,8 @@ 'use strict'; -var api = 'relay-webhooks'; +var api = 'relay-webhooks' + /* global -Promise */ + , Promise = require('./Promise'); var toApiFormat = function(input) { var model = { @@ -23,7 +25,7 @@ module.exports = function(client) { var reqOpts = { uri: api }; - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, find: function(relayWebhookId, callback) { if(typeof relayWebhookId === 'function') { @@ -32,14 +34,13 @@ module.exports = function(client) { } if(!relayWebhookId) { - callback(new Error('relayWebhookId is required')); - return; + return Promise.reject(new Error('relayWebhookId is required')).asCallback(callback); } var options = { uri: api + '/' + relayWebhookId }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, create: function(options, callback) { if(typeof options === 'function') { @@ -48,25 +49,22 @@ module.exports = function(client) { } if(!options) { - callback(new Error('options are required')); - return; + return Promise.reject(new Error('options are required')).asCallback(callback); } if(!options.target) { - callback(new Error('target is required in options')); - return; + return Promise.reject(new Error('target is required in options')).asCallback(callback); } if(!options.domain) { - callback(new Error('domain is required in options')); - return; + return Promise.reject(new Error('domain is required in options')).asCallback(callback); } var reqOpts = { uri: api , json: toApiFormat(options) }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { if(typeof options === 'function') { @@ -75,13 +73,11 @@ module.exports = function(client) { } if(!options) { - callback(new Error('options are required')); - return; + return Promise.reject(new Error('options are required')).asCallback(callback); } if(!options.relayWebhookId) { - callback(new Error('relayWebhookId is required in options')); - return; + return Promise.reject(new Error('relayWebhookId is required in options')).asCallback(callback); } var relayWebhookId = options.relayWebhookId; @@ -89,7 +85,7 @@ module.exports = function(client) { uri: api + '/' + relayWebhookId , json: toApiFormat(options) }; - client.put(reqOpts, callback); + return client.put(reqOpts).asCallback(callback); }, delete: function(relayWebhookId, callback) { if (typeof relayWebhookId === 'function') { @@ -98,15 +94,14 @@ module.exports = function(client) { } if (!relayWebhookId) { - callback(new Error('relayWebhookId is required')); - return; + return Promise.reject(new Error('relayWebhookId is required')).asCallback(callback); } var options = { uri: api + '/' + relayWebhookId }; - client.delete(options, callback); + client.delete(options, callback).asCallback(callback); } }; diff --git a/lib/sendingDomains.js b/lib/sendingDomains.js index b85e357..b335508 100644 --- a/lib/sendingDomains.js +++ b/lib/sendingDomains.js @@ -1,6 +1,8 @@ 'use strict'; var api = 'sending-domains' + /* global -Promise */ + , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); /* @@ -19,7 +21,7 @@ module.exports = function (client) { var options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, find: function (domain, callback) { //retrieve if(typeof domain === 'function') { @@ -28,14 +30,13 @@ module.exports = function (client) { } if(!domain) { - callback(new Error('domain is required')); - return; + return Promise.reject(new Error('domain is required')).asCallback(callback); } var options = { uri: api + '/' + domain }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, create: function (domainBody, callback) { if(typeof domainBody === 'function') { @@ -44,20 +45,18 @@ module.exports = function (client) { } if(!domainBody) { - callback(new Error('domainBody is required')); - return; + return Promise.reject(new Error('domainBody is required')).asCallback(callback); } if(!domainBody.domain) { - callback(new Error('domain is required in the domainBody')); - return; + return Promise.reject(new Error('domain is required in the domainBody')).asCallback(callback); } var options = { uri: api , json: toApiFormat(domainBody) }; - client.post(options, callback); + return client.post(options).asCallback(callback); }, update: function (domainBody, callback) { if(typeof domainBody === 'function') { @@ -66,13 +65,11 @@ module.exports = function (client) { } if(!domainBody) { - callback(new Error('domainBody is required')); - return; + return Promise.reject(new Error('domainBody is required')).asCallback(callback); } if(!domainBody.domain) { - callback(new Error('domain is required in the domainBody')); - return; + return Promise.reject(new Error('domain is required in the domainBody')).asCallback(callback); } var obj = toApiFormat(domainBody); @@ -80,7 +77,7 @@ module.exports = function (client) { uri: api + '/' + obj.domain , json: toApiFormat(domainBody) }; - client.put(options, callback); + return client.put(options).asCallback(callback); }, delete: function(domain, callback) { if (typeof domain === 'function') { @@ -89,21 +86,19 @@ module.exports = function (client) { } if (!domain) { - callback(new Error('domain is required')); - return; + return Promise.reject(new Error('domain is required')).asCallback(callback); } var 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; + return Promise.reject(new Error('domain is required')).asCallback(callback); } var reqOpts = { @@ -114,7 +109,7 @@ module.exports = function (client) { } }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); } }; diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 7745169..41e9c7d 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -2,6 +2,8 @@ var version = require( '../package.json').version , url = require('url') + /* global -Promise */ + , Promise = require('./Promise') , request = require( 'request') , _ = require( 'lodash' ); @@ -106,45 +108,47 @@ 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)) { - err = createSparkPostError(res, body); - return callback(err, res); - } else { - var response = body.results || body; - if(options.debug) { - response.debug = res; + return new Promise(function(resolve, reject) { + request(options, function (err, res, body) { + var invalidCodeRegex = /(5|4)[0-9]{2}/; + if (err) { + reject(err); + } else if (invalidCodeRegex.test(res.statusCode)) { + err = createSparkPostError(res, body); + reject(err); + } else { + var response = body.results || body; + if (options.debug) { + response.debug = res; + } + resolve(response); } - return callback(null, response); - } - }); + }); + }).asCallback(callback); }; SparkPost.prototype.get = function( options, callback ) { options.method = 'GET'; - this.request(options, callback); + return this.request(options).asCallback(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 ) { options.method = 'PUT'; - this.request(options, callback); + return this.request(options).asCallback(callback); }; SparkPost.prototype['delete'] = function( options, callback ) { options.method = 'DELETE'; - this.request(options, callback); + return this.request(options).asCallback(callback); }; SparkPost.SendGridCompatibility = require('./SendGridCompatibility'); diff --git a/lib/subaccounts.js b/lib/subaccounts.js index 85de232..f12984d 100644 --- a/lib/subaccounts.js +++ b/lib/subaccounts.js @@ -1,6 +1,8 @@ 'use strict'; -var api = 'subaccounts'; +var api = 'subaccounts' + /* global -Promise */ + , Promise = require('./Promise'); var toApiFormat = function(input) { var model = {}; @@ -47,7 +49,7 @@ module.exports = function(client) { var options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, find: function(subaccountId, callback) { if(typeof subaccountId === 'function') { @@ -56,14 +58,13 @@ module.exports = function(client) { } if (!subaccountId) { - callback(new Error('subaccountId is required')); - return; + return Promise.reject(new Error('subaccountId is required')).asCallback(callback); } var options = { uri: api + '/' + subaccountId }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, create: function(options, callback) { if(typeof options === 'function') { @@ -72,21 +73,19 @@ module.exports = function(client) { } if (!options) { - callback(new Error('options are required')); - return; + return Promise.reject(new Error('options are required')).asCallback(callback); } var validation = validateCreateOptions(options); if (validation) { - callback(new Error(validation + ' in options')); - return; + return Promise.reject(new Error(validation + ' in options')).asCallback(callback); } var reqOpts = { uri: api, json: toApiFormat(options) }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { if(typeof options === 'function') { @@ -95,13 +94,11 @@ module.exports = function(client) { } if(!options) { - callback(new Error('options are required')); - return; + return Promise.reject(new Error('options are required')).asCallback(callback); } if(!options.subaccountId) { - callback(new Error('subaccountId is required in options')); - return; + return Promise.reject(new Error('subaccountId is required in options')).asCallback(callback); } var subaccountId = options.subaccountId; @@ -109,7 +106,7 @@ module.exports = function(client) { uri: api + '/' + subaccountId, json: toApiFormat(options) }; - client.put(reqOpts, callback); + return client.put(reqOpts).asCallback(callback); } }; diff --git a/lib/suppressionList.js b/lib/suppressionList.js index aa130a9..444dbeb 100644 --- a/lib/suppressionList.js +++ b/lib/suppressionList.js @@ -1,6 +1,8 @@ 'use strict'; var api = 'suppression-list' + /* global -Promise */ + , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); module.exports = function(client) { @@ -11,7 +13,7 @@ module.exports = function(client) { uri: api , qs: parameters }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, checkStatus: function(email, callback) { if(typeof email === 'function') { @@ -20,14 +22,13 @@ module.exports = function(client) { } if(!email) { - callback(new Error('email is required')); - return; + return Promise.reject(new Error('email is required')).asCallback(callback); } var options = { uri: api + '/' + email }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, removeStatus: function(email, callback) { if(typeof email === 'function') { @@ -36,14 +37,13 @@ module.exports = function(client) { } if(!email) { - callback(new Error('email is required')); - return; + return Promise.reject(new Error('email is required')).asCallback(callback); } var options = { uri: api + '/' + email }; - client['delete'](options, callback); + return client.delete(options).asCallback(callback); }, upsert: function(recipients, callback) { var options; @@ -54,8 +54,7 @@ module.exports = function(client) { } if(!recipients) { - callback(new Error('recipient is required')); - return; + return Promise.reject(new Error('recipient is required')).asCallback(callback); } if(!Array.isArray(recipients)) { @@ -68,7 +67,7 @@ module.exports = function(client) { json: { recipients: recipients } }; - client.put(options, callback); + return client.put(options, callback).asCallback(callback); } }; diff --git a/lib/templates.js b/lib/templates.js index b80dbe3..b7ee06e 100644 --- a/lib/templates.js +++ b/lib/templates.js @@ -1,6 +1,8 @@ 'use strict'; var api = 'templates' + /* global -Promise */ + , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); module.exports = function(client) { @@ -9,14 +11,13 @@ module.exports = function(client) { var options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, find: function(options, callback) { options = options || {}; if(!options.id) { - callback(new Error('template id is required')); - return; + return Promise.reject(new Error('template id is required')).asCallback(callback); } var reqOpts = { @@ -28,14 +29,13 @@ module.exports = function(client) { 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; + return Promise.reject(new Error('template object is required')).asCallback(callback); } var reqOpts = { @@ -43,14 +43,13 @@ module.exports = function(client) { , json: toApiFormat(options.template) }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { options = options || {}; if(!options.template) { - callback(new Error('template object is required')); - return; + return Promise.reject(new Error('template object is required')).asCallback(callback); } var object = toApiFormat(options.template) @@ -64,14 +63,28 @@ module.exports = function(client) { reqOpts.qs.update_published = options.update_published; } - client.put(reqOpts, callback); + return client.put(reqOpts).asCallback(callback); + }, + delete: function(id, callback) { + if (typeof id === 'function') { + callback = id; + id = null; + } + + if (!id) { + return Promise.reject(new Error('template id is required')).asCallback(callback); + } + + var options = { + uri: api + '/' + id + }; + return client.delete(options).asCallback(callback); }, preview: function(options, callback) { options = options || {}; if(!options.id) { - callback(new Error('template id is required')); - return; + return Promise.reject(new Error('template id is required')).asCallback(callback); } var reqOpts = { @@ -86,26 +99,9 @@ module.exports = function(client) { reqOpts.qs.draft = options.draft; } - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); } }; - templates['delete'] = function(id, callback) { - if (typeof id === 'function') { - callback = id; - id = null; - } - - if (!id) { - callback(new Error('template id is required')); - return; - } - - var options = { - uri: api + '/' + id - }; - client['delete'](options, callback); - }; - return templates; }; diff --git a/lib/transmissions.js b/lib/transmissions.js index b7317ec..5c99dcb 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -1,6 +1,8 @@ 'use strict'; var api = 'transmissions' + /* global -Promise */ + , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); /* @@ -15,8 +17,7 @@ module.exports = function(client) { options = options || {}; if(!options.transmissionBody) { - callback(new Error('transmissionBody is required')); - return; + return Promise.reject(new Error('transmissionBody is required')).asCallback(callback); } var mappedInput = toApiFormat(options.transmissionBody); @@ -32,7 +33,7 @@ module.exports = function(client) { delete options.num_rcpt_errors; } - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, all: function (options, callback) { if(typeof options === 'function') { @@ -53,7 +54,7 @@ module.exports = function(client) { reqOpts.qs.template_id = options.template_id; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, find: function (transmissionID, callback) { var options = { @@ -66,11 +67,10 @@ module.exports = function(client) { } if(!transmissionID) { - callback(new Error('transmissionID is required')); - return; + return Promise.reject(new Error('transmissionID is required')).asCallback(callback); } - client.get(options, callback); + return client.get(options).asCallback(callback); } }; diff --git a/lib/webhooks.js b/lib/webhooks.js index 852f695..a35354c 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,6 +1,8 @@ 'use strict'; var api = 'webhooks' + /* global -Promise */ + , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); module.exports = function(client) { @@ -20,14 +22,13 @@ module.exports = function(client) { 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; + return Promise.reject(new Error('id is required')).asCallback(callback); } var reqOpts = { uri: api + '/' + options.id @@ -38,7 +39,7 @@ module.exports = function(client) { reqOpts.qs.timezone = options.timezone; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, create: function(webhook, callback) { if(typeof webhook === 'function') { @@ -47,15 +48,14 @@ module.exports = function(client) { } if(!webhook) { - callback(new Error('webhook object is required')); - return; + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } var options = { uri: api , json: toApiFormat(webhook) }; - client.post(options, callback); + return client.post(options).asCallback(callback); }, update: function(webhook, callback) { if(typeof webhook === 'function') { @@ -64,8 +64,7 @@ module.exports = function(client) { } if(!webhook) { - callback(new Error('webhook object is required')); - return; + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } var object = toApiFormat(webhook) @@ -74,19 +73,33 @@ module.exports = function(client) { , json: object }; - client.put(options, callback); + return client.put(options).asCallback(callback); + }, + delete: function(id, callback) { + if (typeof id === 'function') { + callback = id; + id = null; + } + + if (!id) { + return Promise.reject(new Error('id is required')).asCallback(callback); + } + + var options = { + uri: api + '/' + id + }; + + return client.delete(options).asCallback(callback); }, validate: function(options, callback) { options = options || {}; if(!options.id) { - callback(new Error('id is required')); - return; + return Promise.reject(new Error('id is required')).asCallback(callback); } if(!options.message) { - callback(new Error('message is required')); - return; + return Promise.reject(new Error('message is required')).asCallback(callback); } var reqOpts = { @@ -96,14 +109,13 @@ module.exports = function(client) { } }; - 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; + return Promise.reject(new Error('id is required')).asCallback(callback); } var reqOpts = { @@ -115,13 +127,13 @@ module.exports = function(client) { reqOpts.qs.limit = options.limit; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, getDocumentation: function(callback) { var reqOpts = { uri: api + '/events/documentation' }; - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, getSamples: function(options, callback){ var reqOpts = { @@ -138,27 +150,9 @@ module.exports = function(client) { reqOpts.qs.events = options.events; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); } }; - webhooks['delete'] = function(id, callback) { - if (typeof id === 'function') { - callback = id; - id = null; - } - - if (!id) { - callback(new Error('id is required')); - return; - } - - var options = { - uri: api + '/' + id - }; - - client['delete'](options, callback); - }; - return webhooks; }; diff --git a/package.json b/package.json index 4230f4e..4dd7f0f 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "url": "https://github.com/SparkPost/node-sparkpost" }, "author": "Message Systems, Inc.", - "license": "Apache 2.0", + "license": "Apache-2.0", "bugs": { "url": "https://github.com/SparkPost/node-sparkpost/issues" }, @@ -42,6 +42,6 @@ "dependencies": { "json-pointer": "^0.5.0", "lodash": "^4.13.1", - "request": "^2.72.0" + "request": "^2.74.0" } } diff --git a/test/spec/inboundDomains.spec.js b/test/spec/inboundDomains.spec.js index b80e111..a6a0c40 100644 --- a/test/spec/inboundDomains.spec.js +++ b/test/spec/inboundDomains.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,9 @@ describe('Inbound Domains Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - delete: sinon.stub().yields() - + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; inboundDomains = require('../../lib/inboundDomains')(client); diff --git a/test/spec/messageEvents.spec.js b/test/spec/messageEvents.spec.js index e26aee9..af3f0a5 100644 --- a/test/spec/messageEvents.spec.js +++ b/test/spec/messageEvents.spec.js @@ -1,16 +1,18 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); describe('Message Events Library', function() { - var client, templates; + var client; beforeEach(function() { client = { - get: sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})) }; messageEvents = require('../../lib/messageEvents')(client); diff --git a/test/spec/recipientLists.spec.js b/test/spec/recipientLists.spec.js index 670c2be..6c493fd 100644 --- a/test/spec/recipientLists.spec.js +++ b/test/spec/recipientLists.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,10 @@ describe('Recipient Lists Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; recipientLists = require('../../lib/recipientLists')(client); diff --git a/test/spec/relayWebhooks.spec.js b/test/spec/relayWebhooks.spec.js index ea2991f..98d5f19 100644 --- a/test/spec/relayWebhooks.spec.js +++ b/test/spec/relayWebhooks.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,10 @@ describe('Relay Webhooks Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - delete: sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; relayWebhooks = require('../../lib/relayWebhooks')(client); diff --git a/test/spec/sendingDomains.spec.js b/test/spec/sendingDomains.spec.js index 512bc70..a348fff 100644 --- a/test/spec/sendingDomains.spec.js +++ b/test/spec/sendingDomains.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,10 @@ describe('Sending Domains Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - delete: sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; sendingDomains = require('../../lib/sendingDomains')(client); @@ -21,7 +23,7 @@ describe('Sending Domains Library', function() { describe('all Method', function() { it('should call client get method with the appropriate uri', function(done) { - sendingDomains.all(function() { + sendingDomains.all().then(function() { expect(client.get.firstCall.args[0]).to.deep.equal({uri:'sending-domains'}); done(); }); @@ -30,14 +32,14 @@ describe('Sending Domains Library', function() { describe('find Method', function() { it('should call client get method with the appropriate uri', function(done) { - sendingDomains.find('test', function() { + sendingDomains.find('test').then(function() { expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains/test'}); done(); }); }); it('should throw an error if domain is null', function(done) { - sendingDomains.find(null, function(err) { + sendingDomains.find(null).catch(function(err) { expect(err.message).to.equal('domain is required'); expect(client.get).not.to.have.been.called; done(); @@ -59,7 +61,7 @@ describe('Sending Domains Library', function() { domain: "test" }; - sendingDomains.create(domainBody, function(err, data) { + sendingDomains.create(domainBody).then(function(data) { expect(client.post.firstCall.args[0].uri).to.equal('sending-domains'); done(); }); diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 17bb521..019fa37 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -140,11 +140,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(); }); diff --git a/test/spec/subaccounts.spec.js b/test/spec/subaccounts.spec.js index d36d873..d74f80b 100644 --- a/test/spec/subaccounts.spec.js +++ b/test/spec/subaccounts.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,9 +12,9 @@ describe('Subaccounts Library', function () { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})) }; subaccounts = require('../../lib/subaccounts')(client); diff --git a/test/spec/suppressionList.spec.js b/test/spec/suppressionList.spec.js index a661f11..b993800 100644 --- a/test/spec/suppressionList.spec.js +++ b/test/spec/suppressionList.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,10 @@ describe('Suppression List Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; suppressionList = require('../../lib/suppressionList')(client); diff --git a/test/spec/templates.spec.js b/test/spec/templates.spec.js index 4043f2c..41d8a5a 100644 --- a/test/spec/templates.spec.js +++ b/test/spec/templates.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,10 @@ describe('Templates Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; templates = require('../../lib/templates')(client); diff --git a/test/spec/transmissions.spec.js b/test/spec/transmissions.spec.js index bbe50e3..3d436e4 100644 --- a/test/spec/transmissions.spec.js +++ b/test/spec/transmissions.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,8 +12,8 @@ describe('Transmissions Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})) }; transmission = require('../../lib/transmissions')(client); diff --git a/test/spec/webhooks.spec.js b/test/spec/webhooks.spec.js index c5b5a40..777edeb 100644 --- a/test/spec/webhooks.spec.js +++ b/test/spec/webhooks.spec.js @@ -1,7 +1,9 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinonChai = require('sinon-chai') + /* global -Promise */ + , Promise = require('../../lib/Promise'); chai.use(sinonChai); @@ -10,10 +12,10 @@ describe('Webhooks Library', function() { beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().returns(Promise.resolve({})), + post: sinon.stub().returns(Promise.resolve({})), + put: sinon.stub().returns(Promise.resolve({})), + delete: sinon.stub().returns(Promise.resolve({})) }; webhooks = require('../../lib/webhooks')(client); From abb42655e2d87f6dc202bb23d41ac89371b13ecd Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 23 Aug 2016 15:41:48 -0400 Subject: [PATCH 06/27] Switched JSHint for ESLint with SparkPost config (#159) * Switched JSHint for ESLint with SparkPost config * modified lint npm script to remove node_modules path --- .eslintrc | 6 +++ Gruntfile.js | 16 ++---- lib/SendGridCompatibility/Email.js | 53 ++++++++++--------- lib/SendGridCompatibility/index.js | 54 ++++++++++--------- lib/inboundDomains.js | 13 +++-- lib/messageEvents.js | 20 +++---- lib/recipientLists.js | 14 +++-- lib/relayWebhooks.js | 44 +++++++++------- lib/sendingDomains.js | 34 +++++++----- lib/sparkpost.js | 45 ++++++++-------- lib/subaccounts.js | 84 ++++++++++++++++-------------- lib/suppressionList.js | 9 ++-- lib/templates.js | 25 +++++---- lib/toApiFormat.js | 28 +++++----- lib/transmissions.js | 16 +++--- lib/webhooks.js | 35 ++++++++----- package.json | 5 +- test/spec/inboundDomains.spec.js | 1 - test/spec/messageEvents.spec.js | 1 - test/spec/recipientLists.spec.js | 1 - test/spec/relayWebhooks.spec.js | 1 - test/spec/sendingDomains.spec.js | 1 - test/spec/subaccounts.spec.js | 1 - test/spec/suppressionList.spec.js | 1 - test/spec/templates.spec.js | 1 - test/spec/transmissions.spec.js | 1 - test/spec/webhooks.spec.js | 1 - 27 files changed, 277 insertions(+), 234 deletions(-) create mode 100644 .eslintrc diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..2940395 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,6 @@ +{ + "extends": "sparkpost/api", + "globals": { + "Promise": true + } +} diff --git a/Gruntfile.js b/Gruntfile.js index bdbe8b3..b03bf6a 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -19,17 +19,6 @@ module.exports = function(grunt) { grunt.initConfig({ config: config, pkg: grunt.file.readJSON('package.json'), - jshint: { - files: [ - 'index.js', - 'lib/{,*/}*.js', - 'examples/{,*/}*.js' - ], - options: { - reporter: require('jshint-stylish'), - jshintrc: './.jshintrc' - } - }, bump: { options: { files: [ 'package.json' ] @@ -46,6 +35,9 @@ module.exports = function(grunt) { } }, shell: { + lint: { + command: 'npm run lint' + }, coverage: { command : path.join(config.binPath, 'istanbul') + ' cover --report lcov --dir test/reports/ node_modules/mocha/bin/_mocha test/spec -- --reporter ' + reporter, options : { @@ -68,7 +60,7 @@ module.exports = function(grunt) { }); // grunt lint - leverages grunt-contrib-jshint command, lints our code - grunt.registerTask('lint', [ 'jshint' ]); + grunt.registerTask('lint', [ 'shell:lint' ]); // grunt test - runs linting and then our unit tests grunt.registerTask('test', [ diff --git a/lib/SendGridCompatibility/Email.js b/lib/SendGridCompatibility/Email.js index a523122..e107d32 100644 --- a/lib/SendGridCompatibility/Email.js +++ b/lib/SendGridCompatibility/Email.js @@ -5,8 +5,9 @@ * * @param options object that contains initial values */ -function Email(options){ - for (var option in options) { +function Email(options) { + var option; + for (option in options) { this[option] = options[option]; } } @@ -17,85 +18,85 @@ function Email(options){ * @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){ +Email.prototype.addTo = function(address) { + if (this.to === undefined) { this.to = address; - } else if (typeof this.to === 'string'){ + } else if (typeof this.to === 'string') { this.to = [this.to]; this.to.push(address); } else { this.to.push(address); } }; -Email.prototype.setFrom = function (address){ +Email.prototype.setFrom = function(address) { this.from = address; }; -Email.prototype.setSubject = function (subject){ +Email.prototype.setSubject = function(subject) { this.subject = subject; }; -Email.prototype.setText = function (text){ +Email.prototype.setText = function(text) { this.text = text; }; -Email.prototype.setHtml = function (html){ +Email.prototype.setHtml = function(html) { this.html = html; }; -Email.prototype.addHeader = function (key, value){ - if (this.headers === undefined){ +Email.prototype.addHeader = function(key, value) { + if (this.headers === undefined) { this.headers = {}; } this.headers[key] = value; }; -Email.prototype.setHeaders = function (headers){ +Email.prototype.setHeaders = function(headers) { this.headers = headers; }; -Email.prototype.addSubstitution = function (key, value){ - if (this.sub === undefined){ +Email.prototype.addSubstitution = function(key, value) { + if (this.sub === undefined) { this.sub = {}; } - if (typeof value === 'string'){ + if (typeof value === 'string') { this.sub[key] = [value]; } else { this.sub[key] = value; } }; -Email.prototype.setSubstitutions = function (substitutions){ +Email.prototype.setSubstitutions = function(substitutions) { this.sub = substitutions; }; -Email.prototype.addSection = function (key, value){ - if (this.section === undefined){ +Email.prototype.addSection = function(key, value) { + if (this.section === undefined) { this.section = {}; } this.section[key] = value; }; -Email.prototype.setSections = function (sections){ +Email.prototype.setSections = function(sections) { this.section = sections; }; // SparkPost doesn't currently support addUniqueArg, throw an error -Email.prototype.addUniqueArg = function (){ +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 (){ +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 (){ +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 (){ +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 (){ +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 (){ +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 (){ +Email.prototype.addFile = function() { throw new Error('File compatibility is not supported.'); }; diff --git a/lib/SendGridCompatibility/index.js b/lib/SendGridCompatibility/index.js index b5d605e..62dabcc 100644 --- a/lib/SendGridCompatibility/index.js +++ b/lib/SendGridCompatibility/index.js @@ -1,7 +1,8 @@ 'use strict'; -var _ = require('lodash'); -var url = require('url'); -var SparkPost = require('../sparkpost'); +var _ = require('lodash') + , url = require('url') + , SparkPost = require('../sparkpost') + , sendgrid, consolidateSubstitutionData, parseTo, translatePayload; /** * SendGrid compatibility constructor @@ -13,14 +14,15 @@ var SparkPost = require('../sparkpost'); * @param apiKey: api key string * @param options: optional additional options object */ -var sendgrid = function(username, apiKey, options) { +sendgrid = function(username, apiKey, options) { + var urlOpts, opts; options = options || {}; - var urlOpts = { + urlOpts = { protocol: options.protocol , hostname: options.host , port: options.port - } - , opts = { + }; + opts = { endpoint: url.format(urlOpts) }; @@ -35,13 +37,13 @@ var sendgrid = function(username, apiKey, options) { * be translated into a SparkPost payload * @returns object: substitutionData object as per SparkPost payload format */ -var consolidateSubstitutionData = function(payload) { +consolidateSubstitutionData = function(payload) { var substitutionData = {}; - if (payload.sub !== undefined && payload.section !== undefined){ + if (payload.sub !== undefined && payload.section !== undefined) { substitutionData = _.merge(payload.sub, payload.section); - } else if (payload.sub !== undefined){ + } else if (payload.sub !== undefined) { substitutionData = payload.sub; - } else if (payload.section !== undefined){ + } else if (payload.section !== undefined) { substitutionData = payload.section; } return substitutionData; @@ -55,18 +57,18 @@ var consolidateSubstitutionData = function(payload) { * 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'){ +parseTo = function(payload) { + var recipients = [], to, i; + if (typeof payload.to === 'string') { payload.to = [payload.to]; } - for (var i = 0; payload.to.length > i; i++){ - var to = { + for (i = 0; payload.to.length > i; i++) { + to = { address: { email: payload.to[i] } }; - if (payload.toname !== undefined && payload.toname[i] !== undefined){ + if (payload.toname !== undefined && payload.toname[i] !== undefined) { to.address.name = payload.toname[i]; } recipients.push(to); @@ -82,21 +84,21 @@ var parseTo = function(payload){ * be translated into a SparkPost payload * @returns object: translation from SendGrid payload to SparkPost payload */ -var translatePayload = function(payload) { +translatePayload = function(payload) { var sub = consolidateSubstitutionData(payload) , input = { - recipients: [], - from: '', - html: '', - text: '', - subject: '' - }; + recipients: [], + from: '', + html: '', + text: '', + subject: '' + }; - if (payload.to !== undefined){ + if (payload.to !== undefined) { input.recipients = parseTo(payload); } input.from = payload.from; - if (payload.fromname !== undefined){ + if (payload.fromname !== undefined) { input.from = input.from + ' <' + payload.fromname + '>'; } input.subject = payload.subject; diff --git a/lib/inboundDomains.js b/lib/inboundDomains.js index b9d4937..362f9d6 100644 --- a/lib/inboundDomains.js +++ b/lib/inboundDomains.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'inbound-domains' - /* global -Promise */ , Promise = require('./Promise'); module.exports = function(client) { @@ -13,6 +12,8 @@ module.exports = function(client) { return client.get(options).asCallback(callback); }, find: function(domain, callback) { + var options; + if(typeof domain === 'function') { callback = domain; domain = null; @@ -22,12 +23,14 @@ module.exports = function(client) { return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; return client.get(options).asCallback(callback); }, create: function(domain, callback) { + var options; + if(typeof domain === 'function') { callback = domain; domain = null; @@ -37,7 +40,7 @@ module.exports = function(client) { return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api , json: { domain: domain @@ -46,6 +49,8 @@ module.exports = function(client) { return client.post(options, callback).asCallback(callback); }, delete: function(domain, callback) { + var options; + if (typeof domain === 'function') { callback = domain; domain = null; @@ -55,7 +60,7 @@ module.exports = function(client) { return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; return client.delete(options).asCallback(callback); diff --git a/lib/messageEvents.js b/lib/messageEvents.js index 93cd40e..86ce335 100644 --- a/lib/messageEvents.js +++ b/lib/messageEvents.js @@ -6,19 +6,19 @@ var 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: function(parameters, callback) { var arrayParams = [ - 'bounce_classes', - 'campaign_ids', - 'events', - 'friendly_froms', - 'message_ids', - 'recipients', - 'template_ids', - 'transmission_ids' - ] + 'bounce_classes', + 'campaign_ids', + 'events', + 'friendly_froms', + 'message_ids', + 'recipients', + 'template_ids', + 'transmission_ids' + ] , options; arrayParams.forEach(function(paramname) { diff --git a/lib/recipientLists.js b/lib/recipientLists.js index 4904822..1d95ab1 100644 --- a/lib/recipientLists.js +++ b/lib/recipientLists.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'recipient-lists' - /* global -Promise */ , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); @@ -14,13 +13,14 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, find: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { return Promise.reject(new Error('id is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.id }; @@ -32,13 +32,14 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, create: function(options, callback) { + var reqOpts; options = options || {}; if(!options.recipients) { return Promise.reject(new Error('recipients list is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api }; @@ -53,13 +54,14 @@ module.exports = function(client) { return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { return Promise.reject(new Error('recipients list id is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.id }; @@ -74,6 +76,8 @@ module.exports = function(client) { return client.put(reqOpts, callback).asCallback(callback); }, delete: function(id, callback) { + var reqOpts; + if (typeof id === 'function') { callback = id; id = null; @@ -83,7 +87,7 @@ module.exports = function(client) { return Promise.reject(new Error('id is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + id }; return client.delete(reqOpts).asCallback(callback); diff --git a/lib/relayWebhooks.js b/lib/relayWebhooks.js index b825286..233cc32 100644 --- a/lib/relayWebhooks.js +++ b/lib/relayWebhooks.js @@ -1,23 +1,21 @@ 'use strict'; var api = 'relay-webhooks' - /* global -Promise */ - , Promise = require('./Promise'); + , Promise = require('./Promise') + , toApiFormat = function(input) { + var model = { + match: {} + }; -var toApiFormat = function(input) { - var model = { - match: {} - }; - - model.target = input.target; - model.match.domain = input.domain; + model.target = input.target; + model.match.domain = input.domain; - model.name = input.name; - model.auth_token = input.authToken; - model.match.protocol = input.protocol; + model.name = input.name; + model.auth_token = input.authToken; + model.match.protocol = input.protocol; - return model; -}; + return model; + }; module.exports = function(client) { var relayWebhooks = { @@ -28,6 +26,8 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, find: function(relayWebhookId, callback) { + var options; + if(typeof relayWebhookId === 'function') { callback = relayWebhookId; relayWebhookId = null; @@ -37,12 +37,14 @@ module.exports = function(client) { return Promise.reject(new Error('relayWebhookId is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + relayWebhookId }; return client.get(options).asCallback(callback); }, create: function(options, callback) { + var reqOpts; + if(typeof options === 'function') { callback = options; options = null; @@ -60,13 +62,15 @@ module.exports = function(client) { return Promise.reject(new Error('domain is required in options')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api , json: toApiFormat(options) }; return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { + var relayWebhookId, reqOpts; + if(typeof options === 'function') { callback = options; options = null; @@ -80,14 +84,16 @@ module.exports = function(client) { return Promise.reject(new Error('relayWebhookId is required in options')).asCallback(callback); } - var relayWebhookId = options.relayWebhookId; - var reqOpts = { + relayWebhookId = options.relayWebhookId; + reqOpts = { uri: api + '/' + relayWebhookId , json: toApiFormat(options) }; return client.put(reqOpts).asCallback(callback); }, delete: function(relayWebhookId, callback) { + var options; + if (typeof relayWebhookId === 'function') { callback = relayWebhookId; relayWebhookId = null; @@ -97,7 +103,7 @@ module.exports = function(client) { return Promise.reject(new Error('relayWebhookId is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + relayWebhookId }; diff --git a/lib/sendingDomains.js b/lib/sendingDomains.js index b335508..1731145 100644 --- a/lib/sendingDomains.js +++ b/lib/sendingDomains.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'sending-domains' - /* global -Promise */ , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); @@ -14,16 +13,18 @@ var api = 'sending-domains' * - all: retreives a list of sending domains * - find: retreives info about a specific sending domain */ -module.exports = function (client) { +module.exports = function(client) { var sendingDomains = { - all: function (callback) { //list + all: function(callback) { //list var options = { uri: api }; return client.get(options).asCallback(callback); }, - find: function (domain, callback) { //retrieve + find: function(domain, callback) { //retrieve + var options; + if(typeof domain === 'function') { callback = domain; domain = null; @@ -33,12 +34,14 @@ module.exports = function (client) { return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; return client.get(options).asCallback(callback); }, - create: function (domainBody, callback) { + create: function(domainBody, callback) { + var options; + if(typeof domainBody === 'function') { callback = domainBody; domainBody = null; @@ -52,13 +55,15 @@ module.exports = function (client) { return Promise.reject(new Error('domain is required in the domainBody')).asCallback(callback); } - var options = { + options = { uri: api , json: toApiFormat(domainBody) }; return client.post(options).asCallback(callback); }, - update: function (domainBody, callback) { + update: function(domainBody, callback) { + var obj, options; + if(typeof domainBody === 'function') { callback = domainBody; domainBody = null; @@ -72,14 +77,16 @@ module.exports = function (client) { return Promise.reject(new Error('domain is required in the domainBody')).asCallback(callback); } - var obj = toApiFormat(domainBody); - var options = { + obj = toApiFormat(domainBody); + options = { uri: api + '/' + obj.domain , json: toApiFormat(domainBody) }; return client.put(options).asCallback(callback); }, delete: function(domain, callback) { + var options; + if (typeof domain === 'function') { callback = domain; domain = null; @@ -89,19 +96,20 @@ module.exports = function (client) { return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; return client.delete(options).asCallback(callback); }, - verify: function (options, callback) { + verify: function(options, callback) { + var reqOpts; options = options || {}; if(!options.domain) { return Promise.reject(new Error('domain is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.domain + '/verify', json: { dkim_verify: options.verifyDKIM !== false, diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 41e9c7d..aa955b1 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -1,26 +1,26 @@ 'use strict'; -var version = require( '../package.json').version +var version = require('../package.json').version , url = require('url') - /* global -Promise */ , Promise = require('./Promise') - , request = require( 'request') - , _ = require( 'lodash' ); + , 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' }; -var resolveUri = function(origin, 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; @@ -34,9 +34,9 @@ var handleOptions = function(apiKey, options) { return options; }; -var createSparkPostError = function(res, body) { - body = body || {}; +createSparkPostError = function(res, body) { var err = new Error(res.statusMessage); + body = body || {}; err.name = 'SparkPostError'; err.errors = body.errors; err.statusCode = res.statusCode; @@ -44,7 +44,7 @@ var createSparkPostError = function(res, body) { return err; }; -var SparkPost = function(apiKey, options) { +SparkPost = function(apiKey, options) { options = handleOptions(apiKey, options); @@ -79,17 +79,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' ); + 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); @@ -109,15 +110,17 @@ SparkPost.prototype.request = function( options, callback ) { } return new Promise(function(resolve, reject) { - request(options, function (err, res, body) { - var invalidCodeRegex = /(5|4)[0-9]{2}/; + 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 { - var response = body.results || body; + response = body.results || body; if (options.debug) { response.debug = res; } @@ -127,25 +130,25 @@ SparkPost.prototype.request = function( options, callback ) { }).asCallback(callback); }; -SparkPost.prototype.get = function( options, callback ) { +SparkPost.prototype.get = function(options, callback) { options.method = 'GET'; return this.request(options).asCallback(callback); }; -SparkPost.prototype.post = function( options, callback ) { +SparkPost.prototype.post = function(options, callback) { options.method = 'POST'; return this.request(options).asCallback(callback); }; -SparkPost.prototype.put = function( options, callback ) { +SparkPost.prototype.put = function(options, callback) { options.method = 'PUT'; return this.request(options).asCallback(callback); }; -SparkPost.prototype['delete'] = function( options, callback ) { +SparkPost.prototype.delete = function(options, callback) { options.method = 'DELETE'; return this.request(options).asCallback(callback); diff --git a/lib/subaccounts.js b/lib/subaccounts.js index f12984d..db3513b 100644 --- a/lib/subaccounts.js +++ b/lib/subaccounts.js @@ -1,47 +1,45 @@ 'use strict'; var api = 'subaccounts' - /* global -Promise */ - , Promise = require('./Promise'); - -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]; + , Promise = require('./Promise') + , toApiFormat = function(input) { + var model = {} + , keyValidIpsIsArray; + + 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) { + 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'; + return model; } + , validateCreateOptions = function(input) { + if (!input.name) { + return 'name is required'; + } - if (!input.keyLabel) { - return 'keyLabel is required'; - } + if (!input.keyLabel) { + return 'keyLabel is required'; + } - if (!input.keyGrants) { - return 'keyGrants is required'; - } + if (!input.keyGrants) { + return 'keyGrants is required'; + } - return null; -}; + return null; + }; module.exports = function(client) { var subaccounts = { @@ -52,6 +50,8 @@ module.exports = function(client) { return client.get(options).asCallback(callback); }, find: function(subaccountId, callback) { + var options; + if(typeof subaccountId === 'function') { callback = subaccountId; subaccountId = null; @@ -61,12 +61,14 @@ module.exports = function(client) { return Promise.reject(new Error('subaccountId is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + subaccountId }; return client.get(options).asCallback(callback); }, create: function(options, callback) { + var validation, reqOpts; + if(typeof options === 'function') { callback = options; options = null; @@ -76,18 +78,20 @@ module.exports = function(client) { return Promise.reject(new Error('options are required')).asCallback(callback); } - var validation = validateCreateOptions(options); + validation = validateCreateOptions(options); if (validation) { return Promise.reject(new Error(validation + ' in options')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api, json: toApiFormat(options) }; return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { + var subaccountId, reqOpts; + if(typeof options === 'function') { callback = options; options = null; @@ -101,8 +105,8 @@ module.exports = function(client) { return Promise.reject(new Error('subaccountId is required in options')).asCallback(callback); } - var subaccountId = options.subaccountId; - var reqOpts = { + subaccountId = options.subaccountId; + reqOpts = { uri: api + '/' + subaccountId, json: toApiFormat(options) }; diff --git a/lib/suppressionList.js b/lib/suppressionList.js index 444dbeb..91c864b 100644 --- a/lib/suppressionList.js +++ b/lib/suppressionList.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'suppression-list' - /* global -Promise */ , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); @@ -16,6 +15,8 @@ module.exports = function(client) { return client.get(options).asCallback(callback); }, checkStatus: function(email, callback) { + var options; + if(typeof email === 'function') { callback = email; email = null; @@ -25,12 +26,14 @@ module.exports = function(client) { return Promise.reject(new Error('email is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + email }; return client.get(options).asCallback(callback); }, removeStatus: function(email, callback) { + var options; + if(typeof email === 'function') { callback = email; email = null; @@ -40,7 +43,7 @@ module.exports = function(client) { return Promise.reject(new Error('email is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + email }; return client.delete(options).asCallback(callback); diff --git a/lib/templates.js b/lib/templates.js index b7ee06e..e29aaad 100644 --- a/lib/templates.js +++ b/lib/templates.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'templates' - /* global -Promise */ , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); @@ -14,13 +13,14 @@ module.exports = function(client) { return client.get(options).asCallback(callback); }, find: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { return Promise.reject(new Error('template id is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.id }; @@ -32,13 +32,14 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, create: function(options, callback) { + var reqOpts; options = options || {}; if (!options.template) { return Promise.reject(new Error('template object is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api , json: toApiFormat(options.template) }; @@ -46,17 +47,18 @@ module.exports = function(client) { return client.post(reqOpts).asCallback(callback); }, update: function(options, callback) { + var object, reqOpts; options = options || {}; if(!options.template) { return Promise.reject(new Error('template object is required')).asCallback(callback); } - var object = toApiFormat(options.template) - , reqOpts = { - uri: api + '/' + object.id - , json: object - }; + object = toApiFormat(options.template); + reqOpts = { + uri: api + '/' + object.id + , json: object + }; if(options.update_published) { reqOpts.qs = reqOpts.qs || {}; @@ -66,6 +68,8 @@ module.exports = function(client) { return client.put(reqOpts).asCallback(callback); }, delete: function(id, callback) { + var options; + if (typeof id === 'function') { callback = id; id = null; @@ -75,19 +79,20 @@ module.exports = function(client) { return Promise.reject(new Error('template id is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + id }; return client.delete(options).asCallback(callback); }, preview: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { return Promise.reject(new Error('template id is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.id + '/preview' , json: { substitution_data: options.data diff --git a/lib/toApiFormat.js b/lib/toApiFormat.js index 3f33a46..b899a5b 100644 --- a/lib/toApiFormat.js +++ b/lib/toApiFormat.js @@ -1,22 +1,23 @@ 'use strict'; var _ = require('lodash') - , pointer = require('json-pointer'); - -var excludeList = [ - '/substitution_data', - '/tags', - '/metadata', - '/attributes', - '/headers', - '/content/email_rfc822' -]; + , pointer = require('json-pointer') + , excludeList = [ + '/substitution_data', + '/tags', + '/metadata', + '/attributes', + '/headers', + '/content/email_rfc822' + ]; function snakedKeyClone(source) { + var target; + if (!_.isObject(source)) { return source; } - var target = Array.isArray(source) ? [] : {}; + target = Array.isArray(source) ? [] : {}; Object.keys(source).forEach(function(key) { target[_.snakeCase(key)] = snakedKeyClone(source[key]); @@ -26,8 +27,7 @@ function snakedKeyClone(source) { } module.exports = function toApiFormat(source) { - - var excludedObjects = {}; + var excludedObjects = {}, target; // 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. @@ -39,7 +39,7 @@ module.exports = function toApiFormat(source) { }); // Make a clone of the remaining source object but with snaked case keys - var target = snakedKeyClone(source); + target = snakedKeyClone(source); // Reinstated the un-modified objects into the target excludeList.forEach(function(exclusionPointer) { diff --git a/lib/transmissions.js b/lib/transmissions.js index 5c99dcb..7838be4 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'transmissions' - /* global -Promise */ , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); @@ -13,16 +12,17 @@ var api = 'transmissions' module.exports = function(client) { return { - send: function (options, callback) { + send: function(options, callback) { + var reqOpts, mappedInput; options = options || {}; if(!options.transmissionBody) { return Promise.reject(new Error('transmissionBody is required')).asCallback(callback); } - var mappedInput = toApiFormat(options.transmissionBody); + mappedInput = toApiFormat(options.transmissionBody); - var reqOpts = { + reqOpts = { uri: api, json: mappedInput }; @@ -35,13 +35,15 @@ module.exports = function(client) { return client.post(reqOpts).asCallback(callback); }, - all: function (options, callback) { + all: function(options, callback) { + var reqOpts; + if(typeof options === 'function') { callback = options; options = {}; } - var reqOpts = { + reqOpts = { uri: api, qs: {} }; @@ -56,7 +58,7 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, - find: function (transmissionID, callback) { + find: function(transmissionID, callback) { var options = { uri: api + '/' + transmissionID }; diff --git a/lib/webhooks.js b/lib/webhooks.js index a35354c..a338134 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,7 +1,6 @@ 'use strict'; var api = 'webhooks' - /* global -Promise */ , Promise = require('./Promise') , toApiFormat = require('./toApiFormat'); @@ -25,12 +24,14 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, describe: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { return Promise.reject(new Error('id is required')).asCallback(callback); } - var reqOpts = { + + reqOpts = { uri: api + '/' + options.id }; @@ -42,6 +43,8 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, create: function(webhook, callback) { + var options; + if(typeof webhook === 'function') { callback = webhook; webhook = null; @@ -50,7 +53,8 @@ module.exports = function(client) { if(!webhook) { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - var options = { + + options = { uri: api , json: toApiFormat(webhook) }; @@ -58,6 +62,8 @@ module.exports = function(client) { return client.post(options).asCallback(callback); }, update: function(webhook, callback) { + var object, options; + if(typeof webhook === 'function') { callback = webhook; webhook = null; @@ -67,15 +73,18 @@ module.exports = function(client) { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - var object = toApiFormat(webhook) - , options = { - uri: api + '/' + webhook.id - , json: object - }; + object = toApiFormat(webhook); + + options = { + uri: api + '/' + webhook.id + , json: object + }; return client.put(options).asCallback(callback); }, delete: function(id, callback) { + var options; + if (typeof id === 'function') { callback = id; id = null; @@ -85,13 +94,14 @@ module.exports = function(client) { return Promise.reject(new Error('id is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + id }; return client.delete(options).asCallback(callback); }, validate: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { @@ -102,7 +112,7 @@ module.exports = function(client) { return Promise.reject(new Error('message is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.id + '/validate' , json: { message: options.message @@ -112,13 +122,14 @@ module.exports = function(client) { return client.post(reqOpts).asCallback(callback); }, getBatchStatus: function(options, callback) { + var reqOpts; options = options || {}; if(!options.id) { return Promise.reject(new Error('id is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api + '/' + options.id + '/batch-status' }; @@ -135,7 +146,7 @@ module.exports = function(client) { }; return client.get(reqOpts).asCallback(callback); }, - getSamples: function(options, callback){ + getSamples: function(options, callback) { var reqOpts = { uri: api + '/events/samples' }; diff --git a/package.json b/package.json index 4dd7f0f..96c442c 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "description": "A Node.js wrapper for interfacing with your favorite SparkPost APIs", "main": "./lib/sparkpost.js", "scripts": { + "lint": "eslint --fix lib/**", "test": "grunt", "ci": "grunt && grunt coveralls:grunt_coveralls_coverage" }, @@ -23,13 +24,13 @@ "homepage": "https://github.com/SparkPost/node-sparkpost", "devDependencies": { "chai": "1.9.1", + "eslint": "^3.3.1", + "eslint-config-sparkpost": "^1.0.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", diff --git a/test/spec/inboundDomains.spec.js b/test/spec/inboundDomains.spec.js index a6a0c40..9f0f802 100644 --- a/test/spec/inboundDomains.spec.js +++ b/test/spec/inboundDomains.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/messageEvents.spec.js b/test/spec/messageEvents.spec.js index af3f0a5..45d8540 100644 --- a/test/spec/messageEvents.spec.js +++ b/test/spec/messageEvents.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/recipientLists.spec.js b/test/spec/recipientLists.spec.js index 6c493fd..678db2e 100644 --- a/test/spec/recipientLists.spec.js +++ b/test/spec/recipientLists.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/relayWebhooks.spec.js b/test/spec/relayWebhooks.spec.js index 98d5f19..3a5d6cf 100644 --- a/test/spec/relayWebhooks.spec.js +++ b/test/spec/relayWebhooks.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/sendingDomains.spec.js b/test/spec/sendingDomains.spec.js index a348fff..c127be8 100644 --- a/test/spec/sendingDomains.spec.js +++ b/test/spec/sendingDomains.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/subaccounts.spec.js b/test/spec/subaccounts.spec.js index d74f80b..4eb5293 100644 --- a/test/spec/subaccounts.spec.js +++ b/test/spec/subaccounts.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/suppressionList.spec.js b/test/spec/suppressionList.spec.js index b993800..4eec127 100644 --- a/test/spec/suppressionList.spec.js +++ b/test/spec/suppressionList.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/templates.spec.js b/test/spec/templates.spec.js index 41d8a5a..9161cea 100644 --- a/test/spec/templates.spec.js +++ b/test/spec/templates.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/transmissions.spec.js b/test/spec/transmissions.spec.js index 3d436e4..d4aa07f 100644 --- a/test/spec/transmissions.spec.js +++ b/test/spec/transmissions.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); diff --git a/test/spec/webhooks.spec.js b/test/spec/webhooks.spec.js index 777edeb..636d133 100644 --- a/test/spec/webhooks.spec.js +++ b/test/spec/webhooks.spec.js @@ -2,7 +2,6 @@ var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') - /* global -Promise */ , Promise = require('../../lib/Promise'); chai.use(sinonChai); From f012ac1380e2afb484ccafbfa42d942eb7271530 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 23 Aug 2016 15:48:39 -0400 Subject: [PATCH 07/27] Removed support for nodejs versions .10 & .12 (#157) * Removed testing of nodejs versions .10 & .12, added lastest stable, 5, & 6 * latest is 6 so added 4 * reverting the npm version --- .travis.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index cf097c1..08a31ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,8 @@ language: node_js node_js: -- '4.1' -- '4.0' -- '0.12' -- '0.10' +- '4' +- '5' +- '6' before_install: npm install -g grunt-cli install: npm install script: "npm run-script ci" From 0d2afd1a013acc44f103f9f55b5279b537500fc5 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 24 Aug 2016 09:36:11 -0400 Subject: [PATCH 08/27] Switch to using npm scripts instead of grunt (#160) * Remove coveralls task from grunt * removed testing and coverage from grunt * Removed unneed npm deps * Updated docs to remove grunt references * Added npm version scripts & removed Grunt --- .travis.yml | 11 ++- CONTRIBUTING.md | 22 +++++- Gruntfile.js | 74 ------------------- README.md | 8 +- ...DDING_ISSUES.markdown => ADDING_ISSUES.md} | 0 ...YLE_GUIDE.markdown => CODE_STYLE_GUIDE.md} | 0 package.json | 22 ++---- 7 files changed, 36 insertions(+), 101 deletions(-) delete mode 100644 Gruntfile.js rename docs/{ADDING_ISSUES.markdown => ADDING_ISSUES.md} (100%) rename docs/{CODE_STYLE_GUIDE.markdown => CODE_STYLE_GUIDE.md} (100%) diff --git a/.travis.yml b/.travis.yml index 08a31ec..7b1424b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,11 +1,10 @@ language: node_js node_js: -- '4' -- '5' -- '6' -before_install: npm install -g grunt-cli -install: npm install -script: "npm run-script ci" + - '4' + - '5' + - '6' +after_success: + - npm run coveralls notifications: slack: secure: dsz+D/TuylEi+6zqdB5dVqyMlpbpafaBBcAwYIijTK6LuG8KdIdGNSFVX1ro6o3bJFwMvtfxNeK1eFrMy8l6VHZQL0dkXWRmCl/pxLhEntUiYTDwDOtiqy1QLZtv5AqtsdSr1qLiOJtgF6gXk66xipnV2UzjLVVoxzSrdOSnX4U= diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8d7a9bf..1bd221c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,6 +13,24 @@ Current milestone Pull Requests will receive priority review for merging. 3. Write corresponding tests and code (only what is needed to satisfy the issue and tests please) * Include your tests in the 'test' directory in an appropriate test file * Write code to satisfy the tests - * Run tests using ```grunt test``` + * Run tests using ```npm test``` 5. Ensure automated tests pass -6. Submit a new Pull Request applying your feature/fix branch to the develop branch of the SparkPost SDK +6. Submit a new Pull Request applying your feature/fix branch to the develop branch of the SparkPost client library + +## Releases +If you are a collaborator, when you want release a new version, follow these steps. + +1. Make sure all the changes are merged into master +2. Make sure all changes have passed [Travis CI build][1] +3. Determine type of release. We use [Semantic Versioning](http://semver.org/). +4. Update [CHANGELOG.md](CHANGELOG.md) with release notes and commit +5. Run `npm version` command to increment `package.json` version, commit changes, tag changes, and push to upstream. + - Patch -> `npm version patch` + - Minor -> `npm version minor` + - Major -> `npm version major` +6. Once [Travis CI build][1] (from tag) has completed, make sure you're working directory is clean and run `npm publish` + while in the project root. +7. Create a new [Github Release](https://github.com/SparkPost/node-sparkpost/releases) using the new tag. Copy release + notes from the [CHANGELOG.md](CHANGELOG.md). + +[1]: https://travis-ci.org/SparkPost/node-sparkpost diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index b03bf6a..0000000 --- a/Gruntfile.js +++ /dev/null @@ -1,74 +0,0 @@ -var matchdep = require('matchdep') - , gruntTimer = require('time-grunt') - , path = require('path'); - -module.exports = function(grunt) { - // Dynamically load any preexisting grunt tasks/modules - matchdep.filterDev('grunt-*').forEach(grunt.loadNpmTasks); - - // Pretty timing on grunt commands - gruntTimer(grunt); - - var config = { - binPath: path.join('.', 'node_modules', '.bin'), - }; - - var reporter = grunt.option('reporter') || 'xunit-file'; - - // Configure existing grunt tasks and create custom ones - grunt.initConfig({ - config: config, - pkg: grunt.file.readJSON('package.json'), - bump: { - options: { - files: [ 'package.json' ] - , updateConfigs: [ 'pkg' ] - , commit: true - , commitMessage: 'Release %VERSION%' - , commitFiles: [ 'package.json', 'CHANGELOG.md' ] - , createTag: true - , tagName: '%VERSION%' - , tagMessage: '%VERSION%' - , push: true - , pushTo: 'upstream' - , gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d' - } - }, - shell: { - lint: { - command: 'npm run lint' - }, - coverage: { - command : path.join(config.binPath, 'istanbul') + ' cover --report lcov --dir test/reports/ node_modules/mocha/bin/_mocha test/spec -- --reporter ' + reporter, - options : { - stdout : true, - failOnError : true - } - }, - test: { - command: path.join(config.binPath, '_mocha') + ' test/spec' - } - }, - coveralls: { - options: { - force: true - }, - grunt_coveralls_coverage: { - src: 'test/reports/lcov.info' - } - } - }); - - // grunt lint - leverages grunt-contrib-jshint command, lints our code - grunt.registerTask('lint', [ 'shell:lint' ]); - - // grunt test - runs linting and then our unit tests - grunt.registerTask('test', [ - 'lint', - 'shell:test', - 'shell:coverage' - ]); - - // register default grunt command as grunt test - grunt.registerTask('default', [ 'test' ]); -}; diff --git a/README.md b/README.md index dc45c9c..6a0574b 100644 --- a/README.md +++ b/README.md @@ -148,17 +148,15 @@ Click on the desired API to see usage and more information ## Development ### Setup -We use [Grunt](http://gruntjs.com/) for our task runner, so you will also have to install Grunt globally `npm install -g grunt-cli` - Run `npm install` inside the repository to install all the dev dependencies. ### Testing -Once all the dependencies are installed, you can execute the unit tests using `grunt test` +Once all the dependencies are installed, you can execute the unit tests using `npm test` ### Contributing -[Guidelines for adding issues](docs/ADDING_ISSUES.markdown) +[Guidelines for adding issues](docs/ADDING_ISSUES.md) -[Our coding standards](docs/CODE_STYLE_GUIDE.markdown) +[Our coding standards](docs/CODE_STYLE_GUIDE.md) [Submitting pull requests](CONTRIBUTING.md) diff --git a/docs/ADDING_ISSUES.markdown b/docs/ADDING_ISSUES.md similarity index 100% rename from docs/ADDING_ISSUES.markdown rename to docs/ADDING_ISSUES.md diff --git a/docs/CODE_STYLE_GUIDE.markdown b/docs/CODE_STYLE_GUIDE.md similarity index 100% rename from docs/CODE_STYLE_GUIDE.markdown rename to docs/CODE_STYLE_GUIDE.md diff --git a/package.json b/package.json index 96c442c..c7f62dc 100644 --- a/package.json +++ b/package.json @@ -4,9 +4,10 @@ "description": "A Node.js wrapper for interfacing with your favorite SparkPost APIs", "main": "./lib/sparkpost.js", "scripts": { - "lint": "eslint --fix lib/**", - "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", @@ -24,21 +25,14 @@ "homepage": "https://github.com/SparkPost/node-sparkpost", "devDependencies": { "chai": "1.9.1", + "coveralls": "^2.11.12", "eslint": "^3.3.1", "eslint-config-sparkpost": "^1.0.1", - "grunt": "0.4.5", - "grunt-bump": "^0.3.1", - "grunt-coveralls": "^1.0.0", - "grunt-shell": "1.1.1", - "istanbul": "0.3.2", - "matchdep": "0.3.0", - "mocha": "1.21.4", + "istanbul": "^0.4.5", + "mocha": "^3.0.2", "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" + "sinon-chai": "2.5.0" }, "dependencies": { "json-pointer": "^0.5.0", From 6d36260612a42bf74df4b7c4bfaa988f9c777931 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 24 Aug 2016 15:04:19 -0400 Subject: [PATCH 09/27] Removed SendGrid Compatibility (#162) --- lib/SendGridCompatibility/Email.js | 103 ------------ lib/SendGridCompatibility/index.js | 129 --------------- lib/sparkpost.js | 2 - test/spec/SendGridCompatibility/Email.spec.js | 154 ------------------ test/spec/SendGridCompatibility/index.spec.js | 137 ---------------- 5 files changed, 525 deletions(-) delete mode 100644 lib/SendGridCompatibility/Email.js delete mode 100644 lib/SendGridCompatibility/index.js delete mode 100644 test/spec/SendGridCompatibility/Email.spec.js delete mode 100644 test/spec/SendGridCompatibility/index.spec.js diff --git a/lib/SendGridCompatibility/Email.js b/lib/SendGridCompatibility/Email.js deleted file mode 100644 index e107d32..0000000 --- a/lib/SendGridCompatibility/Email.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict'; - -/** - * Email object constructor - * - * @param options object that contains initial values - */ -function Email(options) { - var option; - for (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 62dabcc..0000000 --- a/lib/SendGridCompatibility/index.js +++ /dev/null @@ -1,129 +0,0 @@ -'use strict'; -var _ = require('lodash') - , url = require('url') - , SparkPost = require('../sparkpost') - , sendgrid, consolidateSubstitutionData, parseTo, translatePayload; - -/** - * 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 - */ -sendgrid = function(username, apiKey, options) { - var urlOpts, opts; - options = options || {}; - 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 - */ -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 - */ -parseTo = function(payload) { - var recipients = [], to, i; - if (typeof payload.to === 'string') { - payload.to = [payload.to]; - } - for (i = 0; payload.to.length > i; i++) { - 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 - */ -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/sparkpost.js b/lib/sparkpost.js index aa955b1..b2b2803 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -154,6 +154,4 @@ SparkPost.prototype.delete = function(options, callback) { return this.request(options).asCallback(callback); }; -SparkPost.SendGridCompatibility = require('./SendGridCompatibility'); - module.exports = SparkPost; 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 e4bc46d..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.ok).to.be.true; - expect(err).to.equal(null); - done(); - }); - }); - }); -}); From 1f88477842c2ba4260327e1b2f1946c1592c40f4 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Fri, 26 Aug 2016 13:36:53 -0400 Subject: [PATCH 10/27] Set options.json=true for GET requests (#163) * Setting options.json=true for GET requests * Fixed tests --- lib/sparkpost.js | 4 +--- test/spec/sparkpost.spec.js | 24 ++++++++++++------------ 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/lib/sparkpost.js b/lib/sparkpost.js index b2b2803..8b14bb4 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -101,9 +101,6 @@ SparkPost.prototype.request = function(options, callback) { // set Strict SSL (Always true) options.strictSSL = true; - // set JSON (Always true) - options.json = true; - // default to accepting gzipped responses if (typeof options.gzip === 'undefined') { options.gzip = true; @@ -132,6 +129,7 @@ SparkPost.prototype.request = function(options, callback) { SparkPost.prototype.get = function(options, callback) { options.method = 'GET'; + options.json = true; return this.request(options).asCallback(callback); }; diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 019fa37..78f4c84 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -94,6 +94,7 @@ describe('SparkPost Library', function() { var options = { method: 'GET' , uri: 'get/test' + , json: true , debug: true }; @@ -177,6 +178,7 @@ describe('SparkPost Library', function() { var options = { method: 'GET' , uri: 'https://test.sparkpost.com/test' + , json: true , debug: true }; @@ -196,6 +198,7 @@ describe('SparkPost Library', function() { method: 'GET' , uri: 'https://test.sparkpost.com/test' , gzip: true + , json: true , debug: true }; @@ -235,6 +238,7 @@ describe('SparkPost Library', function() { method: 'GET' , uri: 'https://test.sparkpost.com/test' , gzip: false + , json: true , debug: true }; @@ -286,11 +290,10 @@ describe('SparkPost Library', function() { .reply(200, '{ "ok": true }'); var options = { - method: 'GET' - , uri: 'https://test.sparkpost.com/test' + uri: 'https://test.sparkpost.com/test' }; - client.request(options, function(err, data) { + 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}); @@ -345,14 +348,13 @@ describe('SparkPost Library', function() { .reply(200, '{ "ok": true }'); var options = { - method: 'POST' - , uri: 'https://test.sparkpost.com/test' + uri: 'https://test.sparkpost.com/test' , json: { testingData: 'test data' } }; - client.request(options, function(err, 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}); @@ -407,14 +409,13 @@ describe('SparkPost Library', function() { .reply(200, '{ "ok": true }'); var options = { - method: 'PUT' - , uri: 'https://test.sparkpost.com/test' + uri: 'https://test.sparkpost.com/test' , json: { testingData: 'test data' } }; - client.request(options, function(err, 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}); @@ -469,14 +470,13 @@ describe('SparkPost Library', function() { .reply(200, '{ "ok": true }'); var options = { - method: 'DELETE' - , uri: 'https://test.sparkpost.com/test' + uri: 'https://test.sparkpost.com/test' , json: { testingData: 'test data' } }; - client.request(options, function(err, 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}); From 1faf3fc162e01a3c5d9a1b24c5096203943fbd24 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Fri, 26 Aug 2016 16:12:27 -0400 Subject: [PATCH 11/27] Refactored transmissions library (#158) * Refactored transmissions library & updated tests for promises * merge flub, extra comma in package.json * Updated transmission docs and examples * Documentation updates --- README.md | 48 ++++++------ docs/resources/transmissions.md | 40 ++++++---- examples/baseObject/getDomainsList.js | 9 +++ .../transmissions/get_all_transmissions.js | 10 +++ examples/transmissions/get_transmission.js | 10 +++ .../get_transmissions_by_campaign.js | 10 +++ .../get_transmissions_by_template.js | 10 +++ examples/transmissions/mime_parts.js | 21 +++-- examples/transmissions/rfc822.js | 21 +++-- .../send_transmission_all_fields.js | 67 ++++++++-------- .../send_transmission_with_bcc.js | 51 +++++++------ .../send_transmission_with_cc.js | 55 ++++++++------ .../stored_recipients_inline_content.js | 21 +++-- .../stored_recipients_stored_content.js | 21 +++-- .../transmissions/stored_template_send.js | 23 ++++-- lib/transmissions.js | 43 ++++------- package.json | 8 +- test/spec/transmissions.spec.js | 76 +++++++++---------- 18 files changed, 320 insertions(+), 224 deletions(-) diff --git a/README.md b/README.md index 6a0574b..8982770 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ npm install sparkpost ``` ## Initialization -**new SparkPost(apiKey, options)** - Initialization +**new SparkPost(apiKey[, options])** - Initialization * `apiKey` * Required: yes (unless key is stored in `SPARKPOST_API_KEY` environment variable) @@ -42,20 +42,22 @@ npm install sparkpost * set headers that apply to all requests ## Methods -* **request(options, callback)** +* **request(options[, callback]) → `{Promise}`** * `options` - [see request modules options](https://github.com/mikeal/request#requestoptions-callback) * `options.uri` - can either be a full url or a path that is appended to `options.origin` used at initialization ([url.resolve](http://nodejs.org/api/url.html#url_url_resolve_from_to)) * `options.debug` - setting to `true` includes full response from request client for debugging purposes - * `callback` - executed after task is completed. **required** + * `callback` - executed after task is completed if provided* * standard `callback(err, data)` * `err` - any error that occurred * `data` - results from API call * `data.debug` - full response from request client when `options.debug` is `true` -* **get | post | put | delete(options, callback)** +* **get | post | put | delete(options[, callback]) → `{Promise}`** * `options` - see request options * `callback` - see request options * Request method will be overwritten and set to the same value as the name of these methods. +*callback is optional because all methods return a Promise. + ## Creating a SparkPost Client Passing in an API key @@ -92,25 +94,27 @@ var options = { uri: 'metrics/domains' }; -client.get(options, function(err, data) { - if(err) { +client.get(options) + .then(data => { + console.log(data); + }) + .catch(err => { console.log(err); - return; - } - - console.log(data); -}); + }); ``` ## Send An Email "Hello World" Example -Below is an example of how to send a simple email. Sending an email is known as a *transmission*. By using the send method on the transmissions service that's available from the SparkPost object you instatiate you can pass in a *transmissionBody* object with all the information relevant to the email being sent. The send method also takes a callback method that will let you know if the email was sent successful and if not information about the error that ocurred. +Below is an example of how to send a simple email. Sending an email is known as a *transmission*. By using the send +method on the transmissions service that's available from the SparkPost object you instantiate, you can pass in an +object with all the [transmission attributes](https://developers.sparkpost.com/api/transmissions#header-transmission-attributes) +relevant to the email being sent. The send method will return a promise that will let you know if the email was sent +successful and if not information about the error that occurred. If a callback is passed, it will be executed. ```javascript var SparkPost = require('sparkpost'); -var sp = new SparkPost(''); +var client = new SparkPost(''); -sp.transmissions.send({ - transmissionBody: { +client.transmissions.send({ content: { from: 'testing@sparkpostbox.com', subject: 'Hello, World!', @@ -119,15 +123,15 @@ sp.transmissions.send({ recipients: [ {address: ''} ] - } -}, function(err, res) { - if (err) { + }) + .then(data => { + console.log('Woohoo! You just sent your first mailing!'); + console.log(data); + }) + .catch(err => { console.log('Whoops! Something went wrong'); console.log(err); - } else { - console.log('Woohoo! You just sent your first mailing!'); - } -}); + }); ``` ## SparkPost API Resources Supported in Node Client Library diff --git a/docs/resources/transmissions.md b/docs/resources/transmissions.md index b899f95..230af1a 100644 --- a/docs/resources/transmissions.md +++ b/docs/resources/transmissions.md @@ -1,35 +1,34 @@ # Transmissions -This library provides easy access to the [Transmissions](https://www.sparkpost.com/api#/reference/transmissions/) Resource. +This library provides easy access to the [Transmissions](https://developers.sparkpost.com/api/transmissions) Resource. ## Methods -* **all(options, callback)** +* **all(options[, callback]) → `{Promise}`**
List an overview of all transmissions in the account * `options.campaign_id` - id of the campaign used by the transmission * `options.template_id` - id of the template used by the transmission - * `callback` - executed after task is completed. **required** + * `callback` - executed after task is completed if provided* * standard `callback(err, data)` * `err` - any error that occurred - * `data` - full response from request client -* **find(transmissionID, callback)** + * `data` - results returned by the api +* **find(id[, callback]) → `{Promise}`**
Retrieve the details about a transmission by its ID - * `transmissionID` - id of the transmission you want to look up **required** + * `id` - id of the transmission you want to look up **required** * `callback` - see all function -* **send(options, callback)** +* **send(options[, callback]) → `{Promise}`**
Sends a message by creating a new transmission - * `options.transmissionBody` - a transmission object **required** + * `options` - an object of [transmission attributes](https://developers.sparkpost.com/api/transmissions#header-transmission-attributes) * `options.num_rcpt_errors` - maximum number of recipient errors returned * `callback` - see all function +*callback is optional because all methods return a Promise. ## Getting Started: Your First Mailing ```javascript var SparkPost = require('sparkpost') - , client = new SparkPost('YOUR API KEY'); - -var reqObj = { - transmissionBody: { + , client = new SparkPost('YOUR API KEY') + , options = { campaign_id: 'first-mailing', content: { from: 'you@your-company.com', @@ -39,15 +38,26 @@ var reqObj = { }, substitution_data: {name: 'YOUR FIRST NAME'}, recipients: [{ address: { name: 'YOUR FULL NAME', email: 'YOUR EMAIL ADDRESS' } }] - } -}; + }; + +client.transmissions.send(options) + .then(data => { + console.log('Woohoo! You just sent your first mailing!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); -client.transmissions.send(reqObj, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); } else { console.log('Woohoo! You just sent your first mailing!'); + console.log(data); } }); ``` diff --git a/examples/baseObject/getDomainsList.js b/examples/baseObject/getDomainsList.js index a025fd8..9b4aa25 100644 --- a/examples/baseObject/getDomainsList.js +++ b/examples/baseObject/getDomainsList.js @@ -7,6 +7,15 @@ var key = 'YOURAPIKEY' uri: 'metrics/domains' }; +client.get(options) + .then(data => { + console.log(data); + }) + .catch(err => { + console.log(err); + }); + +// Using a callback client.get(options, function(err, data) { if(err) { console.log(err); diff --git a/examples/transmissions/get_all_transmissions.js b/examples/transmissions/get_all_transmissions.js index f5b735d..8d3be4b 100644 --- a/examples/transmissions/get_all_transmissions.js +++ b/examples/transmissions/get_all_transmissions.js @@ -4,6 +4,16 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +client.transmissions.all() + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); + +// Using a callback client.transmissions.all(function(err, data) { if (err) { console.log(err); diff --git a/examples/transmissions/get_transmission.js b/examples/transmissions/get_transmission.js index 212939d..7374f42 100644 --- a/examples/transmissions/get_transmission.js +++ b/examples/transmissions/get_transmission.js @@ -4,6 +4,16 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +client.transmissions.find('YOUR-TRANsMISSION-KEY') + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); + +// Using a callback client.transmissions.find('YOUR-TRANSMISSION-KEY', function(err, data) { if (err) { console.log(err); diff --git a/examples/transmissions/get_transmissions_by_campaign.js b/examples/transmissions/get_transmissions_by_campaign.js index 75030da..a7040dd 100644 --- a/examples/transmissions/get_transmissions_by_campaign.js +++ b/examples/transmissions/get_transmissions_by_campaign.js @@ -7,6 +7,16 @@ var key = 'YOURAPIKEY' campaign_id: 'my_campaign' }; +client.transmissions.all(options) + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); + +// Using a callback client.transmissions.all(options, function(err, data) { if (err) { console.log(err); diff --git a/examples/transmissions/get_transmissions_by_template.js b/examples/transmissions/get_transmissions_by_template.js index ca28ce7..c70700a 100644 --- a/examples/transmissions/get_transmissions_by_template.js +++ b/examples/transmissions/get_transmissions_by_template.js @@ -7,6 +7,16 @@ var key = 'YOURAPIKEY' template_id: 'my_template' }; +client.transmissions.all(options) + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); + +// Using a callback client.transmissions.all(options, function(err, data) { if (err) { console.log(err); diff --git a/examples/transmissions/mime_parts.js b/examples/transmissions/mime_parts.js index 7050e54..1a4518f 100644 --- a/examples/transmissions/mime_parts.js +++ b/examples/transmissions/mime_parts.js @@ -2,10 +2,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqObj = { - transmissionBody: { + , client = new SparkPost(key) + , options = { recipients: [{ address: { email: 'john.doe@example.com' } }], content: { from: 'From Envelope ', @@ -17,10 +15,19 @@ var reqObj = { open_tracking: true, click_tracking: true } - } -}; + }; + +client.transmissions.send(options) + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqObj, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { diff --git a/examples/transmissions/rfc822.js b/examples/transmissions/rfc822.js index 52b6b07..b5ff2fd 100644 --- a/examples/transmissions/rfc822.js +++ b/examples/transmissions/rfc822.js @@ -2,18 +2,25 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqObj = { - transmissionBody: { + , client = new SparkPost(key) + , options = { recipients: [{address: {email: 'john.doe@example.com'}}], content: { email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World' } - } -}; + }; + +client.transmissions.send(options) + .then(data => { + onsole.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqObj, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { diff --git a/examples/transmissions/send_transmission_all_fields.js b/examples/transmissions/send_transmission_all_fields.js index 637c9b5..b8ae62e 100644 --- a/examples/transmissions/send_transmission_all_fields.js +++ b/examples/transmissions/send_transmission_all_fields.js @@ -1,65 +1,70 @@ -"use strict"; +'use strict'; -var key = "YOURAPIKEY" - , SparkPost = require("sparkpost") - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { options: { open_tracking: true, click_tracking: true }, - campaign_id: "christmas_campaign", - return_path: "bounces-christmas-campaign@flintstone.com", + campaign_id: 'christmas_campaign', metadata: { - user_type: "students" + user_type: 'students' }, substitution_data: { - sender: "Big Store Team" + sender: 'Big Store Team' }, recipients: [ { - return_path: "123@bounces.flintstone.com", address: { - email: "wilma@flintstone.com", - name: "Wilma Flintstone" + email: 'wilma@flintstone.com', + name: 'Wilma Flintstone' }, tags: [ - "greeting", - "prehistoric", - "fred", - "flintstone" + 'greeting', + 'prehistoric', + 'fred', + 'flintstone' ], metadata: { - place: "Bedrock" + place: 'Bedrock' }, substitution_data: { - customer_type: "Platinum" + customer_type: 'Platinum' } } ], content: { from: { - name: "Fred Flintstone", - email: "fred@flintstone.com" + name: 'Fred Flintstone', + email: 'fred@flintstone.com' }, - subject: "Big Christmas savings!", - reply_to: "Christmas Sales ", + subject: 'Big Christmas savings!', + reply_to: 'Christmas Sales ', headers: { - "X-Customer-Campaign-ID": "christmas_campaign" + '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}}

" + 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(options) + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqOpts, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { console.log(data); - console.log("Congrats you can use our client library!"); + console.log('Congrats you can use our client library!'); } }); diff --git a/examples/transmissions/send_transmission_with_bcc.js b/examples/transmissions/send_transmission_with_bcc.js index d91fc32..e0fccaa 100644 --- a/examples/transmissions/send_transmission_with_bcc.js +++ b/examples/transmissions/send_transmission_with_bcc.js @@ -1,48 +1,55 @@ -"use strict"; +'use strict'; -var key = "YOURAPIKEY" - , SparkPost = require("sparkpost") - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { recipients: [ { address: { - email: "original.recipient@example.com", - name: "Original Recipient" + email: 'original.recipient@example.com', + name: 'Original Recipient' }, substitution_data: { - recipient_type: "Original" + recipient_type: 'Original' } }, { address: { - email: "bcc.recipient@example.com", - header_to: "'Original Recipient' " + email: 'bcc.recipient@example.com', + header_to: '"Original Recipient" ' }, substitution_data: { - recipient_type: "BCC" + recipient_type: 'BCC' } } ], content: { from: { - name: "Node BCC Test", - email: "from@example.com" + 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.

" + 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(options) + .then(data => { + console.log(data); + console.log('Congrats! You sent an email with bcc using SparkPost!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqOpts, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { console.log(data); - console.log("Congrats! You sent an email with bcc using SparkPost!"); + 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 index 5813c89..1a2583c 100644 --- a/examples/transmissions/send_transmission_with_cc.js +++ b/examples/transmissions/send_transmission_with_cc.js @@ -1,52 +1,59 @@ -"use strict"; +'use strict'; -var key = "YOURAPIKEY" - , SparkPost = require("sparkpost") - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { recipients: [ { address: { - email: "original.recipient@example.com", - name: "Original Recipient" + email: 'original.recipient@example.com', + name: 'Original Recipient' }, substitution_data: { - recipient_type: "Original" + recipient_type: 'Original' } }, { address: { - email: "cc.recipient@example.com", - name: "Carbon Copy Recipient", - header_to: "'Original Recipient' " + email: 'cc.recipient@example.com', + name: 'Carbon Copy Recipient', + header_to: '"Original Recipient" ' }, substitution_data: { - recipient_type: "CC" + recipient_type: 'CC' } } ], content: { from: { - name: "Node CC Test", - email: "from@example.com" + name: 'Node CC Test', + email: 'from@example.com' }, headers: { - "CC": "'Carbon Copy Recipient' " + '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.

" + 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(options) + .then(data => { + console.log(data); + console.log('Congrats! You sent an email with cc using SparkPost!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqOpts, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { console.log(data); - console.log("Congrats! You sent an email with cc using SparkPost!"); + console.log('Congrats! You sent an email with cc using SparkPost!'); } }); diff --git a/examples/transmissions/stored_recipients_inline_content.js b/examples/transmissions/stored_recipients_inline_content.js index eb5aee6..99c5347 100644 --- a/examples/transmissions/stored_recipients_inline_content.js +++ b/examples/transmissions/stored_recipients_inline_content.js @@ -2,10 +2,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqObj = { - transmissionBody: { + , client = new SparkPost(key) + , options = { recipients: { list_id: 'example-list' }, @@ -15,10 +13,19 @@ var reqObj = { html: '

Hello World

', text: 'Hello World!' } - } -}; + }; + +client.transmissions.send(options) + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqObj, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { diff --git a/examples/transmissions/stored_recipients_stored_content.js b/examples/transmissions/stored_recipients_stored_content.js index 3722545..d8d924d 100644 --- a/examples/transmissions/stored_recipients_stored_content.js +++ b/examples/transmissions/stored_recipients_stored_content.js @@ -2,10 +2,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { + , client = new SparkPost(key) + , options = { recipients: { list_id: 'example-list' }, @@ -14,10 +12,19 @@ var reqOpts = { subject: 'Example Email for Stored List and Template', template_id: 'my-template' } - } -}; + }; + +client.transmissions.send(options) + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqOpts, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { diff --git a/examples/transmissions/stored_template_send.js b/examples/transmissions/stored_template_send.js index aa4c2d3..836e482 100644 --- a/examples/transmissions/stored_template_send.js +++ b/examples/transmissions/stored_template_send.js @@ -2,20 +2,27 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { - campaignId: 'ricks-campaign', + , client = new SparkPost(key) + , options = { + campaign_id: 'ricks-campaign', content: { template_id: 'ricks-template' }, 'num_rcpt_errors': 3, recipients: [{ address: { email: 'rick.sanchez@rickandmorty100years.com', name: 'Rick Sanchez' } }] - } -}; + }; + +client.transmissions.send(options) + .then(data => { + console.log(data); + console.log('What up my glib globs! SparkPost!'); + }) + .catch(err => { + console.log(err); + }); -client.transmissions.send(reqOpts, function(err, data) { +// Using a callback +client.transmissions.send(options, function(err, data) { if (err) { console.log(err); } else { diff --git a/lib/transmissions.js b/lib/transmissions.js index 7838be4..c11d3e0 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -1,8 +1,7 @@ 'use strict'; -var api = 'transmissions' - , Promise = require('./Promise') - , toApiFormat = require('./toApiFormat'); +let Promise = require('./Promise'); +const api = 'transmissions'; /* * "Class" declaration, Transmissions exposes three functions, one for sending a transmission, @@ -13,18 +12,15 @@ module.exports = function(client) { return { send: function(options, callback) { - var reqOpts, mappedInput; - options = options || {}; + var reqOpts; - if(!options.transmissionBody) { - return Promise.reject(new Error('transmissionBody is required')).asCallback(callback); + if(!options || typeof options === 'function') { + return Promise.reject(new Error('options object is required')).asCallback(callback); } - mappedInput = toApiFormat(options.transmissionBody); - reqOpts = { uri: api, - json: mappedInput + json: options }; if (options.num_rcpt_errors) { @@ -45,32 +41,21 @@ module.exports = function(client) { reqOpts = { uri: api, - qs: {} + qs: options }; - if (options.campaign_id) { - reqOpts.qs.campaign_id = options.campaign_id; - } - - if (options.template_id) { - reqOpts.qs.template_id = options.template_id; - } - return client.get(reqOpts).asCallback(callback); }, - find: function(transmissionID, callback) { - var options = { - uri: api + '/' + transmissionID - }; + find: function(id, callback) { + var options; - if(typeof transmissionID === 'function') { - callback = transmissionID; - transmissionID = null; + if (typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!transmissionID) { - return Promise.reject(new Error('transmissionID is required')).asCallback(callback); - } + options = { + uri: api + '/' + id + }; return client.get(options).asCallback(callback); } diff --git a/package.json b/package.json index 11412f8..e1094cb 100644 --- a/package.json +++ b/package.json @@ -24,15 +24,17 @@ }, "homepage": "https://github.com/SparkPost/node-sparkpost", "devDependencies": { - "chai": "1.9.1", + "chai": "^3.5.0", + "chai-as-promised": "^5.3.0", "coveralls": "^2.11.12", "eslint": "^3.3.1", "eslint-config-sparkpost": "^1.0.1", "istanbul": "^0.4.5", "mocha": "^3.0.2", "nock": "^7.2.2", - "sinon": "^1.14.1", - "sinon-chai": "2.5.0" + "sinon": "^1.17.5", + "sinon-as-promised": "^4.0.2", + "sinon-chai": "^2.8.0" }, "dependencies": { "json-pointer": "^0.5.0", diff --git a/test/spec/transmissions.spec.js b/test/spec/transmissions.spec.js index d4aa07f..b002508 100644 --- a/test/spec/transmissions.spec.js +++ b/test/spec/transmissions.spec.js @@ -1,26 +1,36 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai') , Promise = require('../../lib/Promise'); -chai.use(sinonChai); +require('sinon-as-promised'); + +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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})) + 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() { + transmissions.all().then(() => { + 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.all(function() { expect(client.get.firstCall.args[0].uri).to.equal('transmissions'); done(); }); @@ -31,7 +41,7 @@ describe('Transmissions Library', function() { campaign_id: 'test-campaign' }; - transmission.all(options, function(err, data) { + transmissions.all(options, function(err, data) { expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'}); done(); }); @@ -42,7 +52,7 @@ describe('Transmissions Library', function() { template_id: 'test-template' }; - transmission.all(options, function(err, data) { + transmissions.all(options, function(err, data) { expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'}); done(); }); @@ -51,60 +61,44 @@ describe('Transmissions Library', function() { describe('find Method', function() { it('should call client get method with the appropriate uri', function(done) { - transmission.find('test', function() { + transmissions.find('test', function() { expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'}); done(); }); }); - 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 id is null', function() { + return expect(transmissions.find(null)).to.be.rejectedWith('id is required'); }); - 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.find(function() {})).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' - } + campaign_id: 'test-campaign' }; - transmission.send(options, function() { + transmissions.send(options, function() { expect(client.post.firstCall.args[0].uri).to.equal('transmissions'); done(); }); }); - 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 options object is missing', function() { + return expect(transmissions.send(function() {})).to.be.rejectedWith('options object is required'); }); it('should allow num_rcpt_errors to be set in options', function(done) { var options = { - transmissionBody: { - campaign: 'test-campaign' - }, + campaign_id: 'test-campaign', num_rcpt_errors: 3 }; - transmission.send(options, function(err, data) { + transmissions.send(options, function(err, data) { expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); done(); }); @@ -112,14 +106,12 @@ describe('Transmissions Library', function() { it('should leave email_rfc822 content keys intact', function(done) { 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) { + transmissions.send(options, function(err, data) { expect(client.post.firstCall.args[0].json.content).to.have.property('email_rfc822'); done(); }); From 85a8860dc4e5cb4e695724a084bf82f3fa1bdfe9 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Thu, 1 Sep 2016 16:49:38 -0400 Subject: [PATCH 12/27] updated tests and examples (#173) --- docs/resources/transmissions.md | 6 +- examples/baseObject/getDomainsList.js | 9 ++- examples/transmissions/get_transmission.js | 6 +- .../get_transmissions_by_campaign.js | 6 +- .../get_transmissions_by_template.js | 6 +- examples/transmissions/mime_parts.js | 12 +-- examples/transmissions/rfc822.js | 12 +-- .../send_transmission_all_fields.js | 12 +-- .../send_transmission_with_bcc.js | 10 ++- .../send_transmission_with_cc.js | 12 +-- .../stored_recipients_inline_content.js | 12 +-- .../stored_recipients_stored_content.js | 12 +-- .../transmissions/stored_template_send.js | 12 +-- lib/transmissions.js | 19 ++--- test/spec/transmissions.spec.js | 81 +++++++++---------- 15 files changed, 125 insertions(+), 102 deletions(-) diff --git a/docs/resources/transmissions.md b/docs/resources/transmissions.md index 230af1a..b2fa235 100644 --- a/docs/resources/transmissions.md +++ b/docs/resources/transmissions.md @@ -15,10 +15,10 @@ This library provides easy access to the [Transmissions](https://developers.spar Retrieve the details about a transmission by its ID * `id` - id of the transmission you want to look up **required** * `callback` - see all function -* **send(options[, callback]) → `{Promise}`**
+* **send(transmission[, callback]) → `{Promise}`**
Sends a message by creating a new transmission - * `options` - an object of [transmission attributes](https://developers.sparkpost.com/api/transmissions#header-transmission-attributes) - * `options.num_rcpt_errors` - maximum number of recipient errors returned + * `transmission` - an object of [transmission attributes](https://developers.sparkpost.com/api/transmissions#header-transmission-attributes) + * `transmission.num_rcpt_errors` - maximum number of recipient errors returned * `callback` - see all function *callback is optional because all methods return a Promise. diff --git a/examples/baseObject/getDomainsList.js b/examples/baseObject/getDomainsList.js index 9b4aa25..452b106 100644 --- a/examples/baseObject/getDomainsList.js +++ b/examples/baseObject/getDomainsList.js @@ -9,18 +9,21 @@ var key = 'YOURAPIKEY' client.get(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); }); // Using a callback client.get(options, function(err, data) { if(err) { + console.log('Whoops! Something went wrong'); console.log(err); - return; + } else { + console.log('Congrats you can use our client library!'); + console.log(data); } - - console.log(data); }); diff --git a/examples/transmissions/get_transmission.js b/examples/transmissions/get_transmission.js index 7374f42..e39fa12 100644 --- a/examples/transmissions/get_transmission.js +++ b/examples/transmissions/get_transmission.js @@ -6,19 +6,21 @@ var key = 'YOURAPIKEY' client.transmissions.find('YOUR-TRANsMISSION-KEY') .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback client.transmissions.find('YOUR-TRANSMISSION-KEY', function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/get_transmissions_by_campaign.js b/examples/transmissions/get_transmissions_by_campaign.js index a7040dd..47d0ed1 100644 --- a/examples/transmissions/get_transmissions_by_campaign.js +++ b/examples/transmissions/get_transmissions_by_campaign.js @@ -9,19 +9,21 @@ var key = 'YOURAPIKEY' client.transmissions.all(options) .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback client.transmissions.all(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/get_transmissions_by_template.js b/examples/transmissions/get_transmissions_by_template.js index c70700a..bfa6a5b 100644 --- a/examples/transmissions/get_transmissions_by_template.js +++ b/examples/transmissions/get_transmissions_by_template.js @@ -9,19 +9,21 @@ var key = 'YOURAPIKEY' client.transmissions.all(options) .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback client.transmissions.all(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/mime_parts.js b/examples/transmissions/mime_parts.js index 1a4518f..2dcfe91 100644 --- a/examples/transmissions/mime_parts.js +++ b/examples/transmissions/mime_parts.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , transmission = { recipients: [{ address: { email: 'john.doe@example.com' } }], content: { from: 'From Envelope ', @@ -17,21 +17,23 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(options) +client.transmissions.send(transmission) .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(transmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/rfc822.js b/examples/transmissions/rfc822.js index b5ff2fd..bf0a6c7 100644 --- a/examples/transmissions/rfc822.js +++ b/examples/transmissions/rfc822.js @@ -3,28 +3,30 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , transmission = { recipients: [{address: {email: 'john.doe@example.com'}}], content: { email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World' } }; -client.transmissions.send(options) +client.transmissions.send(transmission) .then(data => { - onsole.log(data); console.log('Congrats you can use our client library!'); + onsole.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(transmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/send_transmission_all_fields.js b/examples/transmissions/send_transmission_all_fields.js index b8ae62e..dea0cf7 100644 --- a/examples/transmissions/send_transmission_all_fields.js +++ b/examples/transmissions/send_transmission_all_fields.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , tranmission = { options: { open_tracking: true, click_tracking: true @@ -50,21 +50,23 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(options) +client.transmissions.send(tranmission) .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(tranmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/send_transmission_with_bcc.js b/examples/transmissions/send_transmission_with_bcc.js index e0fccaa..9f24d76 100644 --- a/examples/transmissions/send_transmission_with_bcc.js +++ b/examples/transmissions/send_transmission_with_bcc.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , transmission = { recipients: [ { address: { @@ -35,21 +35,23 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(options) +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); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(transmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats! You sent an email with bcc using SparkPost!'); + console.log(data); } }); diff --git a/examples/transmissions/send_transmission_with_cc.js b/examples/transmissions/send_transmission_with_cc.js index 1a2583c..f2b5286 100644 --- a/examples/transmissions/send_transmission_with_cc.js +++ b/examples/transmissions/send_transmission_with_cc.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , tranmission = { recipients: [ { address: { @@ -39,21 +39,23 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(options) +client.transmissions.send(tranmission) .then(data => { - console.log(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); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(tranmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 index 99c5347..080c312 100644 --- a/examples/transmissions/stored_recipients_inline_content.js +++ b/examples/transmissions/stored_recipients_inline_content.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , transmission = { recipients: { list_id: 'example-list' }, @@ -15,21 +15,23 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(options) +client.transmissions.send(transmission) .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(transmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/stored_recipients_stored_content.js b/examples/transmissions/stored_recipients_stored_content.js index d8d924d..3b4d7ba 100644 --- a/examples/transmissions/stored_recipients_stored_content.js +++ b/examples/transmissions/stored_recipients_stored_content.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , tranmission = { recipients: { list_id: 'example-list' }, @@ -14,21 +14,23 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(options) +client.transmissions.send(tranmission) .then(data => { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(tranmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/transmissions/stored_template_send.js b/examples/transmissions/stored_template_send.js index 836e482..99d1b3a 100644 --- a/examples/transmissions/stored_template_send.js +++ b/examples/transmissions/stored_template_send.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , transmission = { campaign_id: 'ricks-campaign', content: { template_id: 'ricks-template' @@ -12,21 +12,23 @@ var key = 'YOURAPIKEY' recipients: [{ address: { email: 'rick.sanchez@rickandmorty100years.com', name: 'Rick Sanchez' } }] }; -client.transmissions.send(options) +client.transmissions.send(transmission) .then(data => { - console.log(data); console.log('What up my glib globs! SparkPost!'); + console.log(data); }) .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); }); // Using a callback -client.transmissions.send(options, function(err, data) { +client.transmissions.send(transmission, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('What up my glib globs! SparkPost!'); + console.log(data); } }); diff --git a/lib/transmissions.js b/lib/transmissions.js index c11d3e0..2eb350d 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -1,6 +1,7 @@ 'use strict'; -let Promise = require('./Promise'); +let _ = require('lodash') + , Promise = require('./Promise'); const api = 'transmissions'; /* @@ -11,22 +12,22 @@ const api = 'transmissions'; module.exports = function(client) { return { - send: function(options, callback) { + send: function(transmission, callback) { var reqOpts; - if(!options || typeof options === 'function') { - return Promise.reject(new Error('options object is required')).asCallback(callback); + if(!transmission || typeof transmission === 'function') { + return Promise.reject(new Error('transmission object is required')).asCallback(callback); } reqOpts = { uri: api, - json: options + json: _.cloneDeep(transmission), + qs: {} }; - if (options.num_rcpt_errors) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors; - delete options.num_rcpt_errors; + if (reqOpts.json.num_rcpt_errors) { + reqOpts.qs.num_rcpt_errors = reqOpts.json.num_rcpt_errors; + delete reqOpts.json.num_rcpt_errors; } return client.post(reqOpts).asCallback(callback); diff --git a/test/spec/transmissions.spec.js b/test/spec/transmissions.spec.js index b002508..6fefa24 100644 --- a/test/spec/transmissions.spec.js +++ b/test/spec/transmissions.spec.js @@ -2,8 +2,7 @@ var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , Promise = require('../../lib/Promise'); + , sinon = require('sinon'); require('sinon-as-promised'); @@ -24,9 +23,10 @@ describe('Transmissions Library', function() { describe('all Method', function() { it('should call client get method with the appropriate uri', function() { - transmissions.all().then(() => { - expect(client.get.firstCall.args[0].uri).to.equal('transmissions'); - }); + return transmissions.all() + .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) { @@ -36,85 +36,82 @@ describe('Transmissions Library', function() { }); }); - 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' }; - transmissions.all(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'}); - done(); - }); + return transmissions.all(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' }; - transmissions.all(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'}); - done(); - }); + return transmissions.all(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) { - transmissions.find('test', function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'}); - done(); - }); - }); - - it('should throw an error if id is null', function() { - return expect(transmissions.find(null)).to.be.rejectedWith('id is required'); + it('should call client get method with the appropriate uri', function() { + return transmissions.find('test') + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'}); + }); }); it('should throw an error if id is missing', function() { - return expect(transmissions.find(function() {})).to.be.rejectedWith('id is required'); + return expect(transmissions.find()).to.be.rejectedWith('id is required'); }); }); describe('send 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() { + var transmission = { campaign_id: 'test-campaign' }; - transmissions.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 options object is missing', function() { - return expect(transmissions.send(function() {})).to.be.rejectedWith('options object is required'); + 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) { + it('should allow num_rcpt_errors to be set in options', function() { var options = { campaign_id: 'test-campaign', num_rcpt_errors: 3 }; - transmissions.send(options, function(err, data) { - expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); - done(); - }); + return transmissions.send(options) + .then(function() { + expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); + }); }); - it('should leave email_rfc822 content keys intact', function(done) { + it('should leave email_rfc822 content keys intact', function() { var options = { content: { email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World' } }; - transmissions.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'); + }); }); }); }); From aa3ece8e7d17fefe608dc0cf5a5466152b163317 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 6 Sep 2016 15:46:52 -0400 Subject: [PATCH 13/27] Refactored suppression list library (#168) * Updated suppression list lib and tests * Updated suppression list doc and examples * renamed checkStatus & removeStatus to better align with api doc * return promises for all tests * Swapped in new verbs, added jsdoc, updated tests * Updated docs and examples for suppression, added async doc * Updated JSDoc --- docs/async.md | 40 ++++++ docs/resources/suppressionList.md | 50 ++----- examples/suppressionList/checkStatus.js | 14 -- examples/suppressionList/delete.js | 27 ++++ examples/suppressionList/get.js | 27 ++++ examples/suppressionList/list.js | 32 +++++ examples/suppressionList/removeStatus.js | 14 -- .../suppressionList/search_suppressionList.js | 19 --- examples/suppressionList/upsert.js | 43 +++--- examples/suppressionList/upsert_bulk.js | 43 ++++-- lib/sparkpost.js | 8 ++ lib/suppressionList.js | 92 +++++++----- test/spec/suppressionList.spec.js | 136 +++++++----------- 13 files changed, 304 insertions(+), 241 deletions(-) create mode 100644 docs/async.md delete mode 100644 examples/suppressionList/checkStatus.js create mode 100644 examples/suppressionList/delete.js create mode 100644 examples/suppressionList/get.js create mode 100644 examples/suppressionList/list.js delete mode 100644 examples/suppressionList/removeStatus.js delete mode 100644 examples/suppressionList/search_suppressionList.js diff --git a/docs/async.md b/docs/async.md new file mode 100644 index 0000000..e300071 --- /dev/null +++ b/docs/async.md @@ -0,0 +1,40 @@ +# Async Handling + +Callbacks and promises living together... MASS HYSTERIA. Or not! This library handles both of your favorite async strategies. + +### Promises + +All our library methods return promises, so if you're a promise-fan, just do what you normally do. + +```javascript +let client = new SparkPost(key); + +client.templates.get(id) + .then((data) => { + // this is either: + // a) the `results` key of the API response body, or + // b) the full API response body + }) + .catch((err) => { + // handle the sad error + }); +``` + +### Callbacks + +If you're more of a callbacker, that works too. Pass a callback as the last argument and it'll be handled like a regular, error-first callback. + +```javascript +let client = new SparkPost(key); + +client.templates.get(id, (err, data) => { + if (err) { + // handle the sad error + return; + } + + // this is either: + // a) the `results` key of the API response body, or + // b) the full API response body +}); +``` diff --git a/docs/resources/suppressionList.md b/docs/resources/suppressionList.md index 7fdb594..87e40a7 100644 --- a/docs/resources/suppressionList.md +++ b/docs/resources/suppressionList.md @@ -1,45 +1,23 @@ # Suppression List -This library provides easy access to the [Suppression List](https://www.sparkpost.com/api#/reference/suppression-list/) Resource. +This library provides easy access to the [Suppression List](https://developers.sparkpost.com/api/suppression-list) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **search(parameters, callback)** - Perform a filtered search for entries in your suppression list. - * `parameters` - Object of [search parameters](https://www.sparkpost.com/api#/reference/suppression-list/search/search-for-suppression-list-entries) - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **checkStatus(email, callback)** +* **list([parameters])**
+ List all entries in your suppression list, filtered by an optional set of search parameters. + * `parameters` - an object of [search parameters](https://developers.sparkpost.com/api/suppression-list#suppression-list-search-get) +* **get(email)**
+ Retrieve an entry by recipient email. * `email` - `String` email address to check **required** - * `callback` - see search function -* **removeStatus(email, callback)** +* **upsert(listEntries)**
+ Insert or update one or many entries. + * `listEntries` - an object [entry list attributes](https://developers.sparkpost.com/api/suppression-list#header-list-entry-attributes) or `Array` of entry list attribute objects +* **delete(email)**
+ Remove an entry by recipient email. * `email` - `String` email address to remove **required** - * `callback` - see search function -* **upsert(recipient, callback)** - * `recipient` - [Recipient Object](https://www.sparkpost.com/api#/reference/recipient-lists) or `Array` of Recipient Objects - * `callback` - see search function ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); -var parameters = { - from: '2015-05-07T00:00:00+0000' - , to: '2015-05-07T23:59:59+0000' - , limit: 5 -}; - -client.suppressionList.search(parameters, function(err, data) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` - -Check out all the examples provided [here](/examples/suppressionList). +Visit our examples section to see all of [our suppression list resource examples](/examples/suppressionList). diff --git a/examples/suppressionList/checkStatus.js b/examples/suppressionList/checkStatus.js deleted file mode 100644 index 8ff3fdd..0000000 --- a/examples/suppressionList/checkStatus.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.suppressionList.checkStatus('test@test.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/suppressionList/delete.js b/examples/suppressionList/delete.js new file mode 100644 index 0000000..4972441 --- /dev/null +++ b/examples/suppressionList/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.suppressionList.delete('test@test.com') + .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.suppressionList.delete('test@test.com', 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/suppressionList/get.js b/examples/suppressionList/get.js new file mode 100644 index 0000000..39a2e97 --- /dev/null +++ b/examples/suppressionList/get.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.suppressionList.get('test@test.com') + .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.suppressionList.get('test@test.com', 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/suppressionList/list.js b/examples/suppressionList/list.js new file mode 100644 index 0000000..d5883d4 --- /dev/null +++ b/examples/suppressionList/list.js @@ -0,0 +1,32 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , parameters = { + from: '2015-05-07T00:00:00+0000', + to: '2015-05-07T23:59:59+0000', + limit: 5 + }; + +// Promise +client.suppressionList.list(parameters) + .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.suppressionList.list(parameters, 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/suppressionList/removeStatus.js b/examples/suppressionList/removeStatus.js deleted file mode 100644 index d6862a0..0000000 --- a/examples/suppressionList/removeStatus.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.suppressionList.removeStatus('test@test.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/suppressionList/search_suppressionList.js b/examples/suppressionList/search_suppressionList.js deleted file mode 100644 index 8e1ed4c..0000000 --- a/examples/suppressionList/search_suppressionList.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , parameters = { - from: '2015-05-07T00:00:00+0000' - , to: '2015-05-07T23:59:59+0000' - , limit: 5 - }; - -client.suppressionList.search(parameters, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/suppressionList/upsert.js b/examples/suppressionList/upsert.js index 29f23b9..04d1b83 100644 --- a/examples/suppressionList/upsert.js +++ b/examples/suppressionList/upsert.js @@ -3,32 +3,31 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , recipients = [ - { - email: 'test1@test.com' - , transactional: false - , non_transactional: true - , description: 'Test description 1' - }, - { - email: 'test2@test.com' - , transactional: true - , non_transactional: true - , description: 'Test description 2' - }, - { - email: 'test3@test.com' - , transactional: true - , non_transactional: false - , description: 'Test description 3' - } - ]; + , listEntry = { + recipient: 'test1@test.com', + transactional: false, + non_transactional: true, + description: 'Test description 1' + }; -client.suppressionList.upsert(recipients, function(err, data) { +// Promise +client.suppressionList.upsert(listEntry) + .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.suppressionList.upsert(listEntry, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/suppressionList/upsert_bulk.js b/examples/suppressionList/upsert_bulk.js index 29f23b9..a459057 100644 --- a/examples/suppressionList/upsert_bulk.js +++ b/examples/suppressionList/upsert_bulk.js @@ -3,32 +3,45 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , recipients = [ + , listEntries = [ { - email: 'test1@test.com' - , transactional: false - , non_transactional: true - , description: 'Test description 1' + recipient: 'test1@test.com', + transactional: false, + non_transactional: true, + description: 'Test description 1' }, { - email: 'test2@test.com' - , transactional: true - , non_transactional: true - , description: 'Test description 2' + recipient: 'test2@test.com', + transactional: true, + non_transactional: true, + description: 'Test description 2' }, { - email: 'test3@test.com' - , transactional: true - , non_transactional: false - , description: 'Test description 3' + recipient: 'test3@test.com', + transactional: true, + non_transactional: false, + description: 'Test description 3' } ]; -client.suppressionList.upsert(recipients, function(err, data) { +// Promise +client.suppressionList.upsert(listEntries) + .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.suppressionList.upsert(listEntries, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 8b14bb4..e068b83 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -153,3 +153,11 @@ SparkPost.prototype.delete = function(options, callback) { }; 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/suppressionList.js b/lib/suppressionList.js index 91c864b..7d4f985 100644 --- a/lib/suppressionList.js +++ b/lib/suppressionList.js @@ -1,28 +1,38 @@ 'use strict'; -var api = 'suppression-list' - , Promise = require('./Promise') - , 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 }; return client.get(options).asCallback(callback); }, - checkStatus: function(email, callback) { - var options; - if(typeof email === 'function') { - callback = email; - email = null; - } + /** + * Gets a single entry by email address ID + * + * @param {String} email + * @param {RequestCb} [callback] + * @return {Promise} + */ + get: function(email, callback) { + let options; - if(!email) { + if (!email || typeof email === 'function') { return Promise.reject(new Error('email is required')).asCallback(callback); } @@ -31,46 +41,52 @@ module.exports = function(client) { }; return client.get(options).asCallback(callback); }, - removeStatus: function(email, callback) { - var options; - 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) { - return Promise.reject(new Error('email is required')).asCallback(callback); + if (!Array.isArray(listEntries)) { + listEntries = [listEntries]; } options = { - uri: api + '/' + email + uri: api, + json: { recipients: listEntries } }; - return client.delete(options).asCallback(callback); - }, - upsert: function(recipients, callback) { - var options; - if(typeof recipients === 'function') { - callback = recipients; - recipients = null; - } + return client.put(options, callback).asCallback(callback); + }, - if(!recipients) { - return Promise.reject(new Error('recipient is required')).asCallback(callback); - } + /** + * 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 }; - - return client.put(options, callback).asCallback(callback); + return client.delete(options).asCallback(callback); } }; diff --git a/test/spec/suppressionList.spec.js b/test/spec/suppressionList.spec.js index 4eec127..f28be3b 100644 --- a/test/spec/suppressionList.spec.js +++ b/test/spec/suppressionList.spec.js @@ -1,120 +1,90 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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'); }); }); + }); From b11ccff58c3e3d8e35dc672760382b85c50e75e2 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 6 Sep 2016 16:30:28 -0400 Subject: [PATCH 14/27] Refactored subaccounts library (#172) * Updated subaccounts lib and tests * Updated subaccounts doc and examples * updated tests for payloads and cloneDeep * Swapped in new verbs, added jsdoc, updated tests * PR suggestion updates * missed an id check --- docs/resources/subaccounts.md | 48 ++-- examples/subaccounts/create_subaccount.js | 28 ++- examples/subaccounts/get_all_subaccounts.js | 14 -- examples/subaccounts/get_subaccount.js | 16 +- examples/subaccounts/list_subaccounts.js | 26 +++ examples/subaccounts/update_subaccount.js | 23 +- lib/subaccounts.js | 134 +++++------ test/spec/subaccounts.spec.js | 233 +++++--------------- 8 files changed, 193 insertions(+), 329 deletions(-) delete mode 100644 examples/subaccounts/get_all_subaccounts.js create mode 100644 examples/subaccounts/list_subaccounts.js diff --git a/docs/resources/subaccounts.md b/docs/resources/subaccounts.md index 70a7f20..103f75f 100644 --- a/docs/resources/subaccounts.md +++ b/docs/resources/subaccounts.md @@ -1,46 +1,24 @@ # Subaccounts -This library provides easy access to the [Subaccounts](https://www.sparkpost.com/api#/reference/subaccounts) Resource. +This library provides easy access to the [Subaccounts](https://developers.sparkpost.com/api/subaccounts) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **all(callback)** +* **list([callback])**
List a summary of all subaccounts. - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(subaccountId, callback)** - Retrieve details about a specified subaccount by its id - * `subaccountId` - the id of the subaccount you want to look up **required** - * `callback` - see all function -* **create(options, callback)** +* **get(id[, callback])**
+ Get details about a specified subaccount by its id + * `id` - the id of the subaccount you want to look up **required** +* **create(subaccount[, callback])**
Create a new subaccount - * `options.name` - user-friendly name **required** - * `options.keyLabel` - user-friendly identifier for subaccount API key **required** - * `options.keyGrants` - list of grants to give the subaccount API key **required** - * `options.keyValidIps` - list of IPs the subaccount may be used from - * `options.ipPool` - id of the default IP pool assigned to subaccount's transmissions - * `callback` - see all function -* **update(options, callback)** + * `subaccount` - an object of [subaccount attributes](https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes) **required** +* **update(id, subaccount[, callback])**
Updates an existing subaccount - * `options.subaccountId` - the id of the subaccount you want to update **required** - * `options.name` - user-friendly name - * `options.status` - status of the subaccount - * `options.ipPool` - id of the default IP pool assigned to subaccount's transmissions - * `callback` - see all function + * `id` - the id of the subaccount you want to update **required** + * `subaccount` - an object of [updatable subaccount attributes](https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1) **required** ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); - -client.subaccounts.all(function(err, data) { - if(err) { - console.log(err); - return; - } - console.log(data); -}); -``` +Visit our examples section to see all of [our subaccount resource examples](/examples/subaccounts). diff --git a/examples/subaccounts/create_subaccount.js b/examples/subaccounts/create_subaccount.js index e67b2b6..3c94f4d 100644 --- a/examples/subaccounts/create_subaccount.js +++ b/examples/subaccounts/create_subaccount.js @@ -3,20 +3,32 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { - name: 'Test Subaccount' - , keyLabel: 'Test Subaccount key' - , keyGrants: [ - 'smtp/inject' - , 'transmissions/modify' + , subaccount = { + name: 'Test Subaccount', + key_label: 'Test Subaccount key', + key_grants: [ + 'smtp/inject', + 'transmissions/modify' ] }; -client.subaccounts.create(options, function(err, data) { +client.subaccounts.create(subaccount) + .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); + }); + +// Using a callback +client.subaccounts.create(subaccount, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/subaccounts/get_all_subaccounts.js b/examples/subaccounts/get_all_subaccounts.js deleted file mode 100644 index e9c6078..0000000 --- a/examples/subaccounts/get_all_subaccounts.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.subaccounts.all(function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/subaccounts/get_subaccount.js b/examples/subaccounts/get_subaccount.js index 47bf82e..238075c 100644 --- a/examples/subaccounts/get_subaccount.js +++ b/examples/subaccounts/get_subaccount.js @@ -4,11 +4,23 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.subaccounts.find(123, function(err, data) { +client.subaccounts.get('123') + .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); + }); + +// Using a callback +client.subaccounts.get('123', function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/subaccounts/list_subaccounts.js b/examples/subaccounts/list_subaccounts.js new file mode 100644 index 0000000..78e5be7 --- /dev/null +++ b/examples/subaccounts/list_subaccounts.js @@ -0,0 +1,26 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +client.subaccounts.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); + }); + +// Using a callback +client.subaccounts.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/subaccounts/update_subaccount.js b/examples/subaccounts/update_subaccount.js index 3123982..96309a4 100644 --- a/examples/subaccounts/update_subaccount.js +++ b/examples/subaccounts/update_subaccount.js @@ -3,17 +3,28 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { - subaccountId: 123 - , name: 'Test Subaccount' - , status: 'suspended' + , subaccount = { + name: 'Test Subaccount', + status: 'suspended' }; -client.subaccounts.update(options, function(err, data) { +client.subaccounts.update('123', subaccount) + .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); + }); + +// Using a callback +client.subaccounts.update('123', subaccount, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/lib/subaccounts.js b/lib/subaccounts.js index db3513b..55850d8 100644 --- a/lib/subaccounts.js +++ b/lib/subaccounts.js @@ -1,115 +1,85 @@ 'use strict'; -var api = 'subaccounts' - , Promise = require('./Promise') - , toApiFormat = function(input) { - var model = {} - , keyValidIpsIsArray; - - 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) { - 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; - } - , 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 }; return client.get(options).asCallback(callback); }, - find: function(subaccountId, callback) { + /** + * 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(typeof subaccountId === 'function') { - callback = subaccountId; - subaccountId = null; - } - - if (!subaccountId) { - return Promise.reject(new Error('subaccountId is required')).asCallback(callback); + if(!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } options = { - uri: api + '/' + subaccountId + uri: api + '/' + id }; return client.get(options).asCallback(callback); }, - create: function(options, callback) { - var validation, reqOpts; - - if(typeof options === 'function') { - callback = options; - options = null; - } - - if (!options) { - return Promise.reject(new Error('options are required')).asCallback(callback); - } - - validation = validateCreateOptions(options); - if (validation) { - return Promise.reject(new Error(validation + ' in options')).asCallback(callback); + /** + * 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); } reqOpts = { uri: api, - json: toApiFormat(options) + json: subaccount }; return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - var subaccountId, reqOpts; - - 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) { - return Promise.reject(new Error('options are required')).asCallback(callback); + if(!subaccount || typeof subaccount !== 'object') { + return Promise.reject(new Error('subaccount object is required')).asCallback(callback); } - if(!options.subaccountId) { - return Promise.reject(new Error('subaccountId is required in options')).asCallback(callback); - } - - subaccountId = options.subaccountId; reqOpts = { - uri: api + '/' + subaccountId, - json: toApiFormat(options) + uri: api + '/' + id, + json: subaccount }; + return client.put(reqOpts).asCallback(callback); } }; diff --git a/test/spec/subaccounts.spec.js b/test/spec/subaccounts.spec.js index 4eb5293..b4cec81 100644 --- a/test/spec/subaccounts.spec.js +++ b/test/spec/subaccounts.spec.js @@ -1,221 +1,90 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})) + 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'); }); }); }); From c2995709c9062d42d537d22b93b22105727c0e8b Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 7 Sep 2016 08:03:05 -0400 Subject: [PATCH 15/27] Refactored sending domains library (#167) * Updated sending domains lib and tests * Updated sending domains doc and examples * refactored verify to accept all verify attributes * updated tests for payloads and cloneDeep * Updated sending domains verbs, tests, docs, and examples * Updated sending domains verbs, tests, docs, and examples --- docs/resources/sendingDomains.md | 60 ++--- examples/sendingDomains/create.js | 36 +++ .../sendingDomains/create_sendingDomain.js | 24 -- examples/sendingDomains/delete.js | 27 +++ .../sendingDomains/delete_sendingDomain.js | 14 -- examples/sendingDomains/get.js | 27 +++ .../sendingDomains/get_all_sendingDomains.js | 14 -- examples/sendingDomains/get_sendingDomain.js | 14 -- examples/sendingDomains/list.js | 27 +++ .../{update_sendingDomain.js => update.js} | 22 +- examples/sendingDomains/verify.js | 33 +++ .../verify_sendingDomain_default.js | 17 -- .../verify_sendingDomain_dkim_only.js | 18 -- .../verify_sendingDomain_spf_only.js | 18 -- lib/sendingDomains.js | 157 +++++++------ test/spec/sendingDomains.spec.js | 218 ++++++------------ 16 files changed, 345 insertions(+), 381 deletions(-) create mode 100644 examples/sendingDomains/create.js delete mode 100644 examples/sendingDomains/create_sendingDomain.js create mode 100644 examples/sendingDomains/delete.js delete mode 100644 examples/sendingDomains/delete_sendingDomain.js create mode 100644 examples/sendingDomains/get.js delete mode 100644 examples/sendingDomains/get_all_sendingDomains.js delete mode 100644 examples/sendingDomains/get_sendingDomain.js create mode 100644 examples/sendingDomains/list.js rename examples/sendingDomains/{update_sendingDomain.js => update.js} (75%) create mode 100644 examples/sendingDomains/verify.js delete mode 100644 examples/sendingDomains/verify_sendingDomain_default.js delete mode 100644 examples/sendingDomains/verify_sendingDomain_dkim_only.js delete mode 100644 examples/sendingDomains/verify_sendingDomain_spf_only.js diff --git a/docs/resources/sendingDomains.md b/docs/resources/sendingDomains.md index a5199c8..3b3e6c3 100644 --- a/docs/resources/sendingDomains.md +++ b/docs/resources/sendingDomains.md @@ -1,51 +1,35 @@ # Sending Domains -This library provides easy access to the [Sending Domains](https://www.sparkpost.com/api#/reference/sending-domains/) Resource. +This library provides easy access to the [Sending Domains](https://developers.sparkpost.com/api/sending-domains) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **all(callback)** +* **list()**
List an overview of all sending domains in the account. - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(domain, callback)** + +* **get(domain)**
Retrieve a sending domain by its domain name - * `domain` - the name of the domain you want to look up **required** - * `callback` - see all function -* **create(domainBody, callback)** + * `domain` - the domain you want to look up **required** + +* **create(createOpts)**
Create a new sending domain - * `domainBody` - a sending domain object **required** - * `callback` - see all function -* **update(domainBody, callback)** + * `createOpts` - a hash of [sending domain attributes](https://developers.sparkpost.com/api/sending-domains#header-sending-domain-attributes) **required** + +* **update(domain, updateOpts)**
Update an existing sending domain - * `domainBody` - a sending domain object **required** - * `callback` - see all function -* **delete(domain, callback)** + * `domain` - the domain you want to update **required** + * `updateOpts` - a hash of [sending domain attributes](https://developers.sparkpost.com/api/sending-domains#header-sending-domain-attributes) **required** + +* **delete(domain)**
Delete an existing sending domain - * `domain` - the name of the domain you want to delete **required** - * `callback` - see all function -* **verify(options, callback)** + * `domain` - the domain you want to delete **required** + +* **verify(domain, options)**
Validate the specified verification field types for a sending domain - * `options.domain` - the name of the domain you want to verify **required** - * `options.verifyDKIM` - initiates a check against the DKIM record default: `true` - * `options.verifySPF` - initiates a check against the SPF record default: `true` + * `domain` - the domain you want to verify **required** + * `options` - a hash of [verify attributes](https://developers.sparkpost.com/api/sending-domains#header-verify-attributes) **required** ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); - -client.sendingDomains.all(function(err, data) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` - -Check out all the examples provided [here](/examples/sendingDomains). +Visit our examples section to see all of [our sending domains resource examples](/examples/sendingDomains). diff --git a/examples/sendingDomains/create.js b/examples/sendingDomains/create.js new file mode 100644 index 0000000..3820150 --- /dev/null +++ b/examples/sendingDomains/create.js @@ -0,0 +1,36 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , createOpts = { + domain: 'example1.com', + dkim: { + 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQABAoGBAITb3BCRPBi5lGhHdn+1RgC7cjUQEbSb4eFHm+ULRwQ0UIPWHwiVWtptZ09usHq989fKp1g/PfcNzm8c78uTS6gCxfECweFCRK6EdO6cCCr1cfWvmBdSjzYhODUdQeyWZi2ozqd0FhGWoV4VHseh4iLj36DzleTLtOZj3FhAo1WJAkEA68T+KkGeDyWwvttYtuSiQCCTrXYAWTQnkIUxduCp7Ap6tVeIDn3TaXTj74UbEgaNgLhjG4bX//fdeDW6PaK9YwJBAM6xJmwHLPMgwNVjiz3u/6fhY3kaZTWcxtMkXCjh1QE82KzDwqyrCg7EFjTtFysSHCAZxXZMcivGl4TZLHnydJUCQQCx16+M+mAatuiCnvxlQUMuMiSTNK6Amzm45u9v53nlZeY3weYMYFdHdfe1pebMiwrT7MI9clKebz6svYJVmdtXAkApDAc8VuR3WB7TgdRKNWdyGJGfoD1PO1ZE4iinOcoKV+IT1UCY99Kkgg6C7j62n/8T5OpRBvd5eBPpHxP1F9BNAkEA5Nf2VO9lcTetksHdIeKK+F7sio6UZn0Rv7iUo3ALrN1D1cGfWIh2dj3ko1iSreyNVSwGW0ePP27qDmU+u6/Y1g==', + 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB', + selector: 'brisbane', + headers: 'from:to:subject:date' + } + }; + +// Promise +client.sendingDomains.create(createOpts) + .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.sendingDomains.create(createOpts, 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/sendingDomains/create_sendingDomain.js b/examples/sendingDomains/create_sendingDomain.js deleted file mode 100644 index bcb2c86..0000000 --- a/examples/sendingDomains/create_sendingDomain.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var domain = { - domain: 'example1.com', - dkim: { - 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQABAoGBAITb3BCRPBi5lGhHdn+1RgC7cjUQEbSb4eFHm+ULRwQ0UIPWHwiVWtptZ09usHq989fKp1g/PfcNzm8c78uTS6gCxfECweFCRK6EdO6cCCr1cfWvmBdSjzYhODUdQeyWZi2ozqd0FhGWoV4VHseh4iLj36DzleTLtOZj3FhAo1WJAkEA68T+KkGeDyWwvttYtuSiQCCTrXYAWTQnkIUxduCp7Ap6tVeIDn3TaXTj74UbEgaNgLhjG4bX//fdeDW6PaK9YwJBAM6xJmwHLPMgwNVjiz3u/6fhY3kaZTWcxtMkXCjh1QE82KzDwqyrCg7EFjTtFysSHCAZxXZMcivGl4TZLHnydJUCQQCx16+M+mAatuiCnvxlQUMuMiSTNK6Amzm45u9v53nlZeY3weYMYFdHdfe1pebMiwrT7MI9clKebz6svYJVmdtXAkApDAc8VuR3WB7TgdRKNWdyGJGfoD1PO1ZE4iinOcoKV+IT1UCY99Kkgg6C7j62n/8T5OpRBvd5eBPpHxP1F9BNAkEA5Nf2VO9lcTetksHdIeKK+F7sio6UZn0Rv7iUo3ALrN1D1cGfWIh2dj3ko1iSreyNVSwGW0ePP27qDmU+u6/Y1g==', - 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB', - selector: 'brisbane', - headers: 'from:to:subject:date' - } -}; - -client.sendingDomains.create(domain, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/sendingDomains/delete.js b/examples/sendingDomains/delete.js new file mode 100644 index 0000000..6e1f0aa --- /dev/null +++ b/examples/sendingDomains/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.sendingDomains.delete('example1.com') + .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.sendingDomains.delete('example1.com', 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/sendingDomains/delete_sendingDomain.js b/examples/sendingDomains/delete_sendingDomain.js deleted file mode 100644 index 1da0693..0000000 --- a/examples/sendingDomains/delete_sendingDomain.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.sendingDomains.delete('example1.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/sendingDomains/get.js b/examples/sendingDomains/get.js new file mode 100644 index 0000000..46af967 --- /dev/null +++ b/examples/sendingDomains/get.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.sendingDomains.get('example1.com') + .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.sendingDomains.get('example1.com', 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/sendingDomains/get_all_sendingDomains.js b/examples/sendingDomains/get_all_sendingDomains.js deleted file mode 100644 index c9d9e6b..0000000 --- a/examples/sendingDomains/get_all_sendingDomains.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.sendingDomains.all(function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/sendingDomains/get_sendingDomain.js b/examples/sendingDomains/get_sendingDomain.js deleted file mode 100644 index 945e153..0000000 --- a/examples/sendingDomains/get_sendingDomain.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.sendingDomains.find('example1.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/sendingDomains/list.js b/examples/sendingDomains/list.js new file mode 100644 index 0000000..873c07a --- /dev/null +++ b/examples/sendingDomains/list.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.sendingDomains.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.sendingDomains.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/sendingDomains/update_sendingDomain.js b/examples/sendingDomains/update.js similarity index 75% rename from examples/sendingDomains/update_sendingDomain.js rename to examples/sendingDomains/update.js index bb29ce8..97a36a1 100644 --- a/examples/sendingDomains/update_sendingDomain.js +++ b/examples/sendingDomains/update.js @@ -2,10 +2,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') - , client = new SparkPost(key); - - var domain = { - domain: 'example1.com', + , client = new SparkPost(key) + , updateOpts = { dkim: { 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQABAoGBAITb3BCRPBi5lGhHdn+1RgC7cjUQEbSb4eFHm+ULRwQ0UIPWHwiVWtptZ09usHq989fKp1g/PfcNzm8c78uTS6gCxfECweFCRK6EdO6cCCr1cfWvmBdSjzYhODUdQeyWZi2ozqd0FhGWoV4VHseh4iLj36DzleTLtOZj3FhAo1WJAkEA68T+KkGeDyWwvttYtuSiQCCTrXYAWTQnkIUxduCp7Ap6tVeIDn3TaXTj74UbEgaNgLhjG4bX//fdeDW6PaK9YwJBAM6xJmwHLPMgwNVjiz3u/6fhY3kaZTWcxtMkXCjh1QE82KzDwqyrCg7EFjTtFysSHCAZxXZMcivGl4TZLHnydJUCQQCx16+M+mAatuiCnvxlQUMuMiSTNK6Amzm45u9v53nlZeY3weYMYFdHdfe1pebMiwrT7MI9clKebz6svYJVmdtXAkApDAc8VuR3WB7TgdRKNWdyGJGfoD1PO1ZE4iinOcoKV+IT1UCY99Kkgg6C7j62n/8T5OpRBvd5eBPpHxP1F9BNAkEA5Nf2VO9lcTetksHdIeKK+F7sio6UZn0Rv7iUo3ALrN1D1cGfWIh2dj3ko1iSreyNVSwGW0ePP27qDmU+u6/Y1g==', 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB', @@ -14,11 +12,23 @@ var key = 'YOURAPIKEY' } }; -client.sendingDomains.update(domain, function(err, data) { +client.sendingDomains.update('example1.com', updateOpts) + .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); + }); + +// Using a callback +client.sendingDomains.update('example1.com', updateOpts, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/sendingDomains/verify.js b/examples/sendingDomains/verify.js new file mode 100644 index 0000000..a86ab03 --- /dev/null +++ b/examples/sendingDomains/verify.js @@ -0,0 +1,33 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + dkim_verify: true, + spf_verify: true, + abuse_at_verify: true, + postmaster_at_verify: true + }; + +// Promise +client.sendingDomains.verify('example1.com', 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.sendingDomains.verify('example1.com', 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/sendingDomains/verify_sendingDomain_default.js b/examples/sendingDomains/verify_sendingDomain_default.js deleted file mode 100644 index 9184b51..0000000 --- a/examples/sendingDomains/verify_sendingDomain_default.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - domain: 'example1.com' - }; - -client.sendingDomains.verify(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/sendingDomains/verify_sendingDomain_dkim_only.js b/examples/sendingDomains/verify_sendingDomain_dkim_only.js deleted file mode 100644 index 36328ab..0000000 --- a/examples/sendingDomains/verify_sendingDomain_dkim_only.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - domain: 'example1.com' - , verifySPF: false - }; - -client.sendingDomains.verify(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/sendingDomains/verify_sendingDomain_spf_only.js b/examples/sendingDomains/verify_sendingDomain_spf_only.js deleted file mode 100644 index 245c501..0000000 --- a/examples/sendingDomains/verify_sendingDomain_spf_only.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - domain: 'example1.com' - , verifyDKIM: false - }; - -client.sendingDomains.verify(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/lib/sendingDomains.js b/lib/sendingDomains.js index 1731145..faf3c70 100644 --- a/lib/sendingDomains.js +++ b/lib/sendingDomains.js @@ -1,125 +1,142 @@ 'use strict'; -var api = 'sending-domains' - , Promise = require('./Promise') - , 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 - */ +const Promise = require('./Promise'); +const api = 'sending-domains'; + module.exports = function(client) { - var sendingDomains = { - all: function(callback) { //list - var options = { + return { + /** + * Lists all sending domains + * + * @param {RequestCb} [callback] + * @return {Promise} + */ + list: function(callback) { + let options = { uri: api }; + return client.get(options).asCallback(callback); }, - find: function(domain, callback) { //retrieve - var options; - - if(typeof domain === 'function') { - callback = domain; - domain = null; - } - if(!domain) { + /** + * 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); } options = { uri: api + '/' + domain }; + return client.get(options).asCallback(callback); }, - create: function(domainBody, callback) { - var options; - if(typeof domainBody === 'function') { - callback = domainBody; - domainBody = null; - } - - if(!domainBody) { - return Promise.reject(new Error('domainBody is required')).asCallback(callback); - } - - if(!domainBody.domain) { - return Promise.reject(new Error('domain is required in the domainBody')).asCallback(callback); + /** + * 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); } options = { - uri: api - , json: toApiFormat(domainBody) + uri: api, + json: createOpts }; + return client.post(options).asCallback(callback); }, - update: function(domainBody, callback) { - var obj, options; - if(typeof domainBody === 'function') { - callback = domainBody; - domainBody = null; - } - - if(!domainBody) { - return Promise.reject(new Error('domainBody is required')).asCallback(callback); + /** + * 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) { - return Promise.reject(new Error('domain is required in the domainBody')).asCallback(callback); + if (!updateOpts || typeof updateOpts !== 'object') { + return Promise.reject(new Error('update options are required')).asCallback(callback); } - obj = toApiFormat(domainBody); options = { - uri: api + '/' + obj.domain - , json: toApiFormat(domainBody) + uri: api + '/' + domain, + json: updateOpts }; + return client.put(options).asCallback(callback); }, - delete: function(domain, callback) { - var options; - if (typeof domain === 'function') { - callback = domain; - domain = null; - } + /** + * Delete an existing sending domain + * + * @param {string} domain - The domain to delete + * @param {RequestCb} [callback] + * @return {Promise} + */ + delete: function(domain, callback) { + let options; - if (!domain) { + if (typeof domain !== 'string') { return Promise.reject(new Error('domain is required')).asCallback(callback); } options = { uri: api + '/' + domain }; + return client.delete(options).asCallback(callback); }, - verify: function(options, callback) { - var reqOpts; - options = options || {}; - if(!options.domain) { + /** + * 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); + } + reqOpts = { - uri: api + '/' + options.domain + '/verify', - json: { - dkim_verify: options.verifyDKIM !== false, - spf_verify: options.verifySPF !== false - } + uri: api + '/' + domain + '/verify', + json: options }; return client.post(reqOpts).asCallback(callback); } }; - return sendingDomains; }; diff --git a/test/spec/sendingDomains.spec.js b/test/spec/sendingDomains.spec.js index c127be8..e8d3aa7 100644 --- a/test/spec/sendingDomains.spec.js +++ b/test/spec/sendingDomains.spec.js @@ -1,202 +1,124 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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().then(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').then(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).catch(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).then(function(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'); }); }); + }); From 4d3890da30e9bb3ca2c567836d41ac00a0e43653 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 7 Sep 2016 12:32:19 -0400 Subject: [PATCH 16/27] Refactored relay webhooks library (#171) * Updated relayWebhooks lib and tests * Updated relayWebhooks doc and examples * updated tests for payloads and cloneDeep * Swapped in new verbs, added jsdoc, updated tests * removed callback from doc * updated example link on doc --- docs/resources/relayWebhooks.md | 59 ++---- examples/relayWebhooks/create.js | 34 ++++ examples/relayWebhooks/create_relayWebhook.js | 19 -- examples/relayWebhooks/delete.js | 27 +++ examples/relayWebhooks/delete_relayWebhook.js | 15 -- examples/relayWebhooks/find_relayWebhook.js | 15 -- examples/relayWebhooks/get.js | 27 +++ .../relayWebhooks/get_all_relayWebhooks.js | 14 -- examples/relayWebhooks/list.js | 27 +++ examples/relayWebhooks/update.js | 30 +++ examples/relayWebhooks/update_relayWebhook.js | 18 -- lib/relayWebhooks.js | 147 +++++++-------- test/spec/relayWebhooks.spec.js | 171 ++++++------------ 13 files changed, 283 insertions(+), 320 deletions(-) create mode 100644 examples/relayWebhooks/create.js delete mode 100644 examples/relayWebhooks/create_relayWebhook.js create mode 100644 examples/relayWebhooks/delete.js delete mode 100644 examples/relayWebhooks/delete_relayWebhook.js delete mode 100644 examples/relayWebhooks/find_relayWebhook.js create mode 100644 examples/relayWebhooks/get.js delete mode 100644 examples/relayWebhooks/get_all_relayWebhooks.js create mode 100644 examples/relayWebhooks/list.js create mode 100644 examples/relayWebhooks/update.js delete mode 100644 examples/relayWebhooks/update_relayWebhook.js diff --git a/docs/resources/relayWebhooks.md b/docs/resources/relayWebhooks.md index 2fc7f95..36d3ccf 100644 --- a/docs/resources/relayWebhooks.md +++ b/docs/resources/relayWebhooks.md @@ -1,55 +1,26 @@ # Relay Webhooks -This library provides easy access to the [Relay Webhooks](https://www.sparkpost.com/api#/reference/relay-webhooks/) Resource. +This library provides easy access to the [Relay Webhooks](https://developers.sparkpost.com/api/relay-webhooks) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **all(options, callback)** +* **list()**
List all relay webhooks. - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(webhookId, callback)** - Retrieve details about a specified relay webhook by its id - * `webhookId` - the id of the relay webhook you want to look up **required** - * `callback` - see all function -* **create(options, callback)** +* **get(id)**
+ Get details about a specified relay webhook by its id + * `id` - the id of the relay webhook you want to look up **required** +* **create(webhook)**
Create a new relay webhook - * `options.target` - url of the target to which to POST relay batches **required** - * `options.domain` - inbound domain associated with this webhook **required** - * `options.name` - user-friendly name - * `options.authToken` - authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target - * `options.protocol` - inbound messaging protocol associated with this webhook - * `callback` - see all function -* **update(options, callback)** + * `webhook` - an object of [relay webhook attributes](https://developers.sparkpost.com/api/relay-webhooks#header-relay-webhooks-object-properties) **required** +* **update(id, webhook)**
Update an existing relay webhook - * `options.webhookId` - the id of the relay webhook you want to update **required** - * `options.target` - url of the target to which to POST relay batches - * `options.domain` - inbound domain associated with this webhook - * `options.name` - user-friendly name - * `options.authToken` - authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target - * `options.protocol` - inbound messaging protocol associated with this webhook - * `callback` - see all function -* **delete(webhookId, callback)** + * `id` - the id of the relay webhook you want to update **required** + * `webhook` - an object of [relay webhook attributes](https://developers.sparkpost.com/api/relay-webhooks#header-relay-webhooks-object-properties) **required** +* **delete(id)**
Delete an existing relay webhook - * `webhookId` - the id of the webhook you want to delete **required** - * `callback` - see all function + * `id` - the id of the relay webhook you want to delete **required** ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); - -client.relayWebhooks.all(function(err, data) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` - -Check out all the examples provided [here](/examples/relayWebhooks). +Visit our examples section to see all of [our relay webhook resource examples](/examples/relayWebhooks). diff --git a/examples/relayWebhooks/create.js b/examples/relayWebhooks/create.js new file mode 100644 index 0000000..e8cd656 --- /dev/null +++ b/examples/relayWebhooks/create.js @@ -0,0 +1,34 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , webhook = { + name: 'Test Relay Webhook', + target: 'http://client.test.com/test-webhook', + match: { + domain: 'inbound.example.com' + } + }; + + // Promise +client.relayWebhooks.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.relayWebhooks.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/relayWebhooks/create_relayWebhook.js b/examples/relayWebhooks/create_relayWebhook.js deleted file mode 100644 index 0544e0d..0000000 --- a/examples/relayWebhooks/create_relayWebhook.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - name: 'Test Relay Webhook' - , target: 'http://client.test.com/test-webhook' - , domain: 'inbound.example.com' - }; - -client.relayWebhooks.create(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/relayWebhooks/delete.js b/examples/relayWebhooks/delete.js new file mode 100644 index 0000000..552880f --- /dev/null +++ b/examples/relayWebhooks/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.relayWebhooks.delete('123456789') + .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.relayWebhooks.delete('123456789', 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/relayWebhooks/delete_relayWebhook.js b/examples/relayWebhooks/delete_relayWebhook.js deleted file mode 100644 index beec64d..0000000 --- a/examples/relayWebhooks/delete_relayWebhook.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , relayWebhookId = '123456789'; - -client.relayWebhooks.delete(relayWebhookId, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/relayWebhooks/find_relayWebhook.js b/examples/relayWebhooks/find_relayWebhook.js deleted file mode 100644 index b42eb3e..0000000 --- a/examples/relayWebhooks/find_relayWebhook.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , relayWebhookId = '123456789'; - -client.relayWebhooks.find(relayWebhookId, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/relayWebhooks/get.js b/examples/relayWebhooks/get.js new file mode 100644 index 0000000..7774989 --- /dev/null +++ b/examples/relayWebhooks/get.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.relayWebhooks.get('123456789') + .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.relayWebhooks.get('123456789', 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/relayWebhooks/get_all_relayWebhooks.js b/examples/relayWebhooks/get_all_relayWebhooks.js deleted file mode 100644 index 5729fe3..0000000 --- a/examples/relayWebhooks/get_all_relayWebhooks.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.relayWebhooks.all(function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/relayWebhooks/list.js b/examples/relayWebhooks/list.js new file mode 100644 index 0000000..03d2d94 --- /dev/null +++ b/examples/relayWebhooks/list.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.relayWebhooks.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.relayWebhooks.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/relayWebhooks/update.js b/examples/relayWebhooks/update.js new file mode 100644 index 0000000..3ce7047 --- /dev/null +++ b/examples/relayWebhooks/update.js @@ -0,0 +1,30 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , webhook = { + target: 'http://client.test.com/test-webhook' + }; + +// Promise +client.relayWebhooks.update('123456789', 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.relayWebhooks.update('123456789', 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/relayWebhooks/update_relayWebhook.js b/examples/relayWebhooks/update_relayWebhook.js deleted file mode 100644 index ed3ef7e..0000000 --- a/examples/relayWebhooks/update_relayWebhook.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - relayWebhookId: '123456789' - , target: 'http://client.test.com/test-webhook' - }; - -client.relayWebhooks.update(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/lib/relayWebhooks.js b/lib/relayWebhooks.js index 233cc32..5a0d7af 100644 --- a/lib/relayWebhooks.js +++ b/lib/relayWebhooks.js @@ -1,115 +1,106 @@ 'use strict'; -var api = 'relay-webhooks' - , Promise = require('./Promise') - , 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 }; return client.get(reqOpts).asCallback(callback); }, - find: function(relayWebhookId, callback) { - var options; - - if(typeof relayWebhookId === 'function') { - callback = relayWebhookId; - relayWebhookId = null; - } - - if(!relayWebhookId) { - return Promise.reject(new Error('relayWebhookId is required')).asCallback(callback); + /** + * 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); } options = { - uri: api + '/' + relayWebhookId + uri: api + '/' + id }; return client.get(options).asCallback(callback); }, - create: function(options, callback) { - var reqOpts; - - if(typeof options === 'function') { - callback = options; - options = null; - } - - if(!options) { - return Promise.reject(new Error('options are required')).asCallback(callback); - } - - if(!options.target) { - return Promise.reject(new Error('target is required in options')).asCallback(callback); - } - - if(!options.domain) { - return Promise.reject(new Error('domain is required in options')).asCallback(callback); + /** + * 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); } reqOpts = { uri: api - , json: toApiFormat(options) + , json: webhook }; return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - var relayWebhookId, reqOpts; - - if(typeof options === 'function') { - callback = options; - options = null; - } - - if(!options) { - return Promise.reject(new Error('options are required')).asCallback(callback); + /** + * 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) { - return Promise.reject(new Error('relayWebhookId is required in options')).asCallback(callback); + if(!webhook || typeof webhook !== 'object') { + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - relayWebhookId = options.relayWebhookId; reqOpts = { - uri: api + '/' + relayWebhookId - , json: toApiFormat(options) + uri: api + '/' + id + , json: webhook }; + return client.put(reqOpts).asCallback(callback); }, - delete: function(relayWebhookId, callback) { - var options; - - if (typeof relayWebhookId === 'function') { - callback = relayWebhookId; - relayWebhookId = null; - } - - if (!relayWebhookId) { - return Promise.reject(new Error('relayWebhookId is required')).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); } options = { - uri: api + '/' + relayWebhookId + uri: api + '/' + id }; - client.delete(options, callback).asCallback(callback); + return client.delete(options, callback).asCallback(callback); } }; - - return relayWebhooks; }; diff --git a/test/spec/relayWebhooks.spec.js b/test/spec/relayWebhooks.spec.js index 3a5d6cf..35aaa35 100644 --- a/test/spec/relayWebhooks.spec.js +++ b/test/spec/relayWebhooks.spec.js @@ -1,164 +1,101 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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'); }); }); }); From b5ad4241e046481fdde5d0fff26ad60ca482e565 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 7 Sep 2016 14:54:46 -0400 Subject: [PATCH 17/27] Swapped in new verbs, added jsdoc, updated tests (#177) --- docs/resources/inboundDomains.md | 40 ++----- examples/inboundDomains/create.js | 28 +++++ .../inboundDomains/create_inboundDomain.js | 14 --- examples/inboundDomains/delete.js | 27 +++++ .../inboundDomains/delete_inboundDomain.js | 14 --- examples/inboundDomains/find_inboundDomain.js | 14 --- examples/inboundDomains/get.js | 27 +++++ .../inboundDomains/get_all_inboundDomains.js | 14 --- examples/inboundDomains/list.js | 27 +++++ lib/inboundDomains.js | 74 +++++++----- test/spec/inboundDomains.spec.js | 113 +++++++----------- 11 files changed, 201 insertions(+), 191 deletions(-) create mode 100644 examples/inboundDomains/create.js delete mode 100644 examples/inboundDomains/create_inboundDomain.js create mode 100644 examples/inboundDomains/delete.js delete mode 100644 examples/inboundDomains/delete_inboundDomain.js delete mode 100644 examples/inboundDomains/find_inboundDomain.js create mode 100644 examples/inboundDomains/get.js delete mode 100644 examples/inboundDomains/get_all_inboundDomains.js create mode 100644 examples/inboundDomains/list.js diff --git a/docs/resources/inboundDomains.md b/docs/resources/inboundDomains.md index 7c5746f..630e59c 100644 --- a/docs/resources/inboundDomains.md +++ b/docs/resources/inboundDomains.md @@ -1,42 +1,22 @@ # Inbound Domains -This library provides easy access to the [Inbound Domains](https://developers.sparkpost.com/api#/reference/inbound-domains/) Resource. +This library provides easy access to the [Inbound Domains](https://developers.sparkpost.com/api/inbound-domains) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **all(callback)** +* **list()**
List an overview of all inbound domains in the account. - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(domain, callback)** - Retrieve a inbound domain by its domain name +* **get(domain)**
+ Get an inbound domain by its domain name * `domain` - the name of the domain you want to look up **required** - * `callback` - see all function -* **create(domain, callback)** +* **create(createOpts)**
Create a new inbound domain - * `domain` - the name of the domain you want to create **required** - * `callback` - see all function -* **delete(domain, callback)** + * `createOpts` - a hash of [inbound domain attributes](https://developers.sparkpost.com/api/inbound-domains#header-inbound-domains-attributes) **required** +* **delete(domain)**
Delete an existing inbound domain * `domain` - the name of the domain you want to delete **required** - * `callback` - see all function ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); - -client.inboundDomains.all(function(err, data) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` - -Check out all the examples provided [here](/examples/inboundDomains). +Visit our examples section to see all of [our inbound domains resource examples](/examples/inboundDomains). diff --git a/examples/inboundDomains/create.js b/examples/inboundDomains/create.js new file mode 100644 index 0000000..5f4477c --- /dev/null +++ b/examples/inboundDomains/create.js @@ -0,0 +1,28 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , createOpts = {domain: 'example1.com'}; + +// Promise +client.inboundDomains.create(createOpts) + .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.inboundDomains.create(createOpts, 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/inboundDomains/create_inboundDomain.js b/examples/inboundDomains/create_inboundDomain.js deleted file mode 100644 index f803134..0000000 --- a/examples/inboundDomains/create_inboundDomain.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.inboundDomains.create('example1.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/inboundDomains/delete.js b/examples/inboundDomains/delete.js new file mode 100644 index 0000000..b5c9c1d --- /dev/null +++ b/examples/inboundDomains/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.inboundDomains.delete('example1.com') + .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.inboundDomains.delete('example1.com', 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/inboundDomains/delete_inboundDomain.js b/examples/inboundDomains/delete_inboundDomain.js deleted file mode 100644 index d3056f5..0000000 --- a/examples/inboundDomains/delete_inboundDomain.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.inboundDomains.delete('example1.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/inboundDomains/find_inboundDomain.js b/examples/inboundDomains/find_inboundDomain.js deleted file mode 100644 index 9b83178..0000000 --- a/examples/inboundDomains/find_inboundDomain.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.inboundDomains.find('example1.com', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/inboundDomains/get.js b/examples/inboundDomains/get.js new file mode 100644 index 0000000..b36abfe --- /dev/null +++ b/examples/inboundDomains/get.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.inboundDomains.get('example1.com') + .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.inboundDomains.get('example1.com', 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/inboundDomains/get_all_inboundDomains.js b/examples/inboundDomains/get_all_inboundDomains.js deleted file mode 100644 index 59bcf34..0000000 --- a/examples/inboundDomains/get_all_inboundDomains.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.inboundDomains.all(function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/inboundDomains/list.js b/examples/inboundDomains/list.js new file mode 100644 index 0000000..0bfacd5 --- /dev/null +++ b/examples/inboundDomains/list.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.inboundDomains.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.inboundDomains.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/lib/inboundDomains.js b/lib/inboundDomains.js index 362f9d6..4901c89 100644 --- a/lib/inboundDomains.js +++ b/lib/inboundDomains.js @@ -1,25 +1,33 @@ 'use strict'; -var api = 'inbound-domains' - , Promise = require('./Promise'); +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 }; return client.get(options).asCallback(callback); }, - find: function(domain, callback) { - var options; + /** + * Get an inbound domain by its domain name + * + * @param {string} domain + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(domain, callback) { + let options; - if(typeof domain === 'function') { - callback = domain; - domain = null; - } - - if(!domain) { + if(!domain || typeof domain !== 'string') { return Promise.reject(new Error('domain is required')).asCallback(callback); } @@ -28,35 +36,37 @@ module.exports = function(client) { }; return client.get(options).asCallback(callback); }, - create: function(domain, callback) { - var options; - - 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) { - return Promise.reject(new Error('domain is required')).asCallback(callback); + if(!createOpts || typeof createOpts !== 'object') { + return Promise.reject(new Error('create options are required')).asCallback(callback); } options = { uri: api - , json: { - domain: domain - } + , json: createOpts }; return client.post(options, callback).asCallback(callback); }, + /** + * Delete an existing inbound domain + * + * @param {string} domain + * @param {RequestCb} [callback] + * @returns {Promise} + */ delete: function(domain, callback) { - var options; - - if (typeof domain === 'function') { - callback = domain; - domain = null; - } + let options; - if (!domain) { + if (!domain || typeof domain !== 'string') { return Promise.reject(new Error('domain is required')).asCallback(callback); } @@ -66,6 +76,4 @@ module.exports = function(client) { return client.delete(options).asCallback(callback); } }; - - return inboundDomains; }; diff --git a/test/spec/inboundDomains.spec.js b/test/spec/inboundDomains.spec.js index 9f0f802..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') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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'); }); }); }); From 1840444a0efcba1d833db6c2662942f62bc8d393 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 7 Sep 2016 16:36:43 -0400 Subject: [PATCH 18/27] Refactored recipient lists library (#166) * Updated recipient list lib and tests * Updated recipient list doc and examples * updated create and update tests for payload, deep copy * Updated recipient list verbs, jsdoc, tests, docs, and examples --- docs/resources/recipientLists.md | 55 ++-- .../{create_recipientList.js => create.js} | 19 +- examples/recipientLists/delete.js | 27 ++ .../recipientLists/delete_recipientList.js | 14 - examples/recipientLists/get.js | 31 +++ .../recipientLists/get_all_recipientLists.js | 14 - examples/recipientLists/get_recipientList.js | 17 -- .../get_recipientList_with_recipients.js | 18 -- examples/recipientLists/list.js | 27 ++ .../{update_recipientList.js => update.js} | 26 +- lib/recipientLists.js | 134 ++++++---- test/spec/recipientLists.spec.js | 246 +++++++++--------- 12 files changed, 355 insertions(+), 273 deletions(-) rename examples/recipientLists/{create_recipientList.js => create.js} (58%) create mode 100644 examples/recipientLists/delete.js delete mode 100644 examples/recipientLists/delete_recipientList.js create mode 100644 examples/recipientLists/get.js delete mode 100644 examples/recipientLists/get_all_recipientLists.js delete mode 100644 examples/recipientLists/get_recipientList.js delete mode 100644 examples/recipientLists/get_recipientList_with_recipients.js create mode 100644 examples/recipientLists/list.js rename examples/recipientLists/{update_recipientList.js => update.js} (58%) diff --git a/docs/resources/recipientLists.md b/docs/resources/recipientLists.md index 32a6812..f88cd40 100644 --- a/docs/resources/recipientLists.md +++ b/docs/resources/recipientLists.md @@ -1,50 +1,31 @@ # Recipient Lists -This library provides easy access to the [Recipient Lists](https://www.sparkpost.com/api#/reference/recipient-lists/) Resource. +This library provides easy access to the [Recipient Lists](https://developers.sparkpost.com/api/recipient-lists) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **all(callback)** +* **list()**
List a summary of all recipient lists. - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(options, callback)** + +* **get(id[, options])**
Retrieve details about a specified recipient list by its id - * `options.id` - the id of the recipient list you want to look up **required** - * `options.show_recipients` - specifies whether to retrieve the recipients Default: `false` - * `callback` - see all function -* **create(options, callback)** + * `options.show_recipients` - specifies whether to retrieve the recipients | Default: `false` + +* **create(recipientList)**
Create a new recipient list - * `options.recipients` - an array of recipients to add to the list **required** - * `options.num_rcpt_errors` - limit the number of recipient errors returned - * `callback` - see all function -* **update(options, callback)** + * `recipientList` - an object of [recipient list](https://developers.sparkpost.com/api/recipient-lists#header-recipient-list-attributes) **required** + * `recipientList.num_rcpt_errors` - limit the number of recipient errors returned | Default: all errors returned + +* **update(id, recipientList)**
Update an existing recipient list - * `options.id` - the id of the recipient list you want to update **required** - * `options.recipients` - an array of recipients to add to the list **required** - * `options.num_rcpt_errors` - limit the number of recipient errors returned - * `callback` - see all function -* **delete(id, callback)** + * `recipientList` - an object of [recipient list](https://developers.sparkpost.com/api/recipient-lists#header-recipient-list-attributes) **required** + * `recipientList.num_rcpt_errors` - limit the number of recipient errors returned | Default: all errors returned + +* **delete(id)**
Delete an existing recipient list * `id` - the id of the recipient list you want to delete **required** - * `callback` - see all function ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); - -client.recipientLists.all(function(err, data) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` - -Check out all the examples provided [here](/examples/recipientLists). +Visit our examples section to see all of [our recipient list resource examples](/examples/recipientLists). diff --git a/examples/recipientLists/create_recipientList.js b/examples/recipientLists/create.js similarity index 58% rename from examples/recipientLists/create_recipientList.js rename to examples/recipientLists/create.js index 0ea932b..4925c74 100644 --- a/examples/recipientLists/create_recipientList.js +++ b/examples/recipientLists/create.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , recipientList = { id: 'UNIQUE_TEST_ID' , name: 'Test Recipient List' , recipients: [ @@ -25,11 +25,24 @@ var key = 'YOURAPIKEY' ] }; -client.recipientLists.create(options, function(err, data) { +// Promise +client.recipientLists.create(recipientList) + .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.recipientLists.create(recipientList, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/recipientLists/delete.js b/examples/recipientLists/delete.js new file mode 100644 index 0000000..3268f40 --- /dev/null +++ b/examples/recipientLists/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.recipientLists.delete('UNIQUE_TEST_ID') + .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.recipientLists.delete('UNIQUE_TEST_ID', 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/recipientLists/delete_recipientList.js b/examples/recipientLists/delete_recipientList.js deleted file mode 100644 index 97bc883..0000000 --- a/examples/recipientLists/delete_recipientList.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.recipientLists['delete']('UNIQUE_TEST_ID', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/recipientLists/get.js b/examples/recipientLists/get.js new file mode 100644 index 0000000..7754715 --- /dev/null +++ b/examples/recipientLists/get.js @@ -0,0 +1,31 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + id: 'UNIQUE_TEST_ID' + , show_recipients: true + }; + +// Promise +client.recipientLists.get(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.recipientLists.get(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/recipientLists/get_all_recipientLists.js b/examples/recipientLists/get_all_recipientLists.js deleted file mode 100644 index b0ea723..0000000 --- a/examples/recipientLists/get_all_recipientLists.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.recipientLists.all(function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/recipientLists/get_recipientList.js b/examples/recipientLists/get_recipientList.js deleted file mode 100644 index 3180c9b..0000000 --- a/examples/recipientLists/get_recipientList.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'UNIQUE_TEST_ID' - }; - -client.recipientLists.find(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/recipientLists/get_recipientList_with_recipients.js b/examples/recipientLists/get_recipientList_with_recipients.js deleted file mode 100644 index 12007f7..0000000 --- a/examples/recipientLists/get_recipientList_with_recipients.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'UNIQUE_TEST_ID' - , show_recipients: true - }; - -client.recipientLists.find(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/recipientLists/list.js b/examples/recipientLists/list.js new file mode 100644 index 0000000..19bf1f7 --- /dev/null +++ b/examples/recipientLists/list.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.recipientLists.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.recipientLists.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/recipientLists/update_recipientList.js b/examples/recipientLists/update.js similarity index 58% rename from examples/recipientLists/update_recipientList.js rename to examples/recipientLists/update.js index 5814ed6..3a881d4 100644 --- a/examples/recipientLists/update_recipientList.js +++ b/examples/recipientLists/update.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , options = { + , recipientList = { id: 'EXISTING_TEST_ID' , name: 'Test Recipient List' , recipients: [ @@ -11,13 +11,13 @@ var key = 'YOURAPIKEY' address: { email: 'test1@test.com' } - } - , { + }, + { address: { email: 'test2@test.com' } - } - , { + }, + { address: { email: 'test3@test.com' } @@ -25,11 +25,23 @@ var key = 'YOURAPIKEY' ] }; -client.recipientLists.update(options, function(err, data) { +// Promise +client.recipientLists.update(recipientList) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log(err); + }); + +// Callback +client.recipientLists.update(recipientList, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/lib/recipientLists.js b/lib/recipientLists.js index 1d95ab1..1644038 100644 --- a/lib/recipientLists.js +++ b/lib/recipientLists.js @@ -1,98 +1,138 @@ 'use strict'; -var api = 'recipient-lists' - , Promise = require('./Promise') - , 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 }; 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) { + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (!id) { return Promise.reject(new Error('id is required')).asCallback(callback); } reqOpts = { - uri: api + '/' + options.id + uri: api + '/' + id, + qs: options }; - if(options.show_recipients) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.show_recipients = options.show_recipients; - } - return client.get(reqOpts).asCallback(callback); }, - create: function(options, callback) { + + + /** + * 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; - options = options || {}; - if(!options.recipients) { - return Promise.reject(new Error('recipients list is required')).asCallback(callback); + if (!recipientList || typeof recipientList !== 'object' || !recipientList.recipients) { + return Promise.reject(new Error('recipient list is required')).asCallback(callback); } reqOpts = { - uri: api + uri: api, + json: recipientList, + qs: { + num_rcpt_errors: recipientList.num_rcpt_errors + } }; - if (options.num_rcpt_errors) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors; - delete options.num_rcpt_errors; - } - - reqOpts.json = toApiFormat(options); - return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { + + /** + * 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; - options = options || {}; - if(!options.id) { - return Promise.reject(new Error('recipients list id is required')).asCallback(callback); + if (!id) { + return Promise.reject(new Error('recipient list id is required')).asCallback(callback); } - 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 + } + }; - return client.put(reqOpts, callback).asCallback(callback); + return client.put(reqOpts).asCallback(callback); }, + + /** + * 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 (typeof id === 'function') { - callback = id; - id = null; - } - - if (!id) { + if (!id || typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } reqOpts = { uri: api + '/' + id }; + return client.delete(reqOpts).asCallback(callback); } }; - return recipientLists; }; diff --git a/test/spec/recipientLists.spec.js b/test/spec/recipientLists.spec.js index 678db2e..e0bee3f 100644 --- a/test/spec/recipientLists.spec.js +++ b/test/spec/recipientLists.spec.js @@ -1,175 +1,189 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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'); }); + }); + }); From b55f9c447a98cf12dff2c8c2e916dd97d019ff7e Mon Sep 17 00:00:00 2001 From: Aydrian Date: Mon, 24 Oct 2016 15:05:55 -0400 Subject: [PATCH 19/27] Refactored webhooks library (#170) * Updated webhooks lib and tests * Updated webhooks doc and examples * updated tests for payloads and cloneDeep --- docs/resources/webhooks.md | 52 ++++-- examples/webhooks/create_webhook.js | 22 ++- examples/webhooks/delete_webhook.js | 16 +- examples/webhooks/describe_webhook.js | 18 +- examples/webhooks/getBatchStatus.js | 18 +- examples/webhooks/getDocumentation.js | 14 +- examples/webhooks/getSamples.js | 14 +- examples/webhooks/get_all_webhooks.js | 14 +- examples/webhooks/update_webhook.js | 20 +- examples/webhooks/validate_webhook.js | 18 +- lib/webhooks.js | 61 +++--- test/spec/webhooks.spec.js | 259 +++++++++++--------------- 12 files changed, 291 insertions(+), 235 deletions(-) diff --git a/docs/resources/webhooks.md b/docs/resources/webhooks.md index 1a27242..120a216 100644 --- a/docs/resources/webhooks.md +++ b/docs/resources/webhooks.md @@ -1,63 +1,77 @@ # Webhooks -This library provides easy access to the [Webhooks](https://www.sparkpost.com/api#/reference/webhooks/) Resource. +This library provides easy access to the [Webhooks](https://developers.sparkpost.com/api/webhooks) Resource. ## Methods -* **all(options, callback)** +* **all([options, callback]) → `{Promise}`**
List currently extant webhooks. * `options.timezone` - `String` Standard timezone identification Default: `UTC` - * `callback` - executed after task is completed. **required** + * `callback` - executed after task is completed if provided* * standard `callback(err, data)` * `err` - any error that occurred * `data` - full response from request client -* **describe(options, callback)** +* **describe(options[, callback]) → `{Promise}`**
Retrieve details about a specified webhook by its id * `options.id` - the id of the webhook you want to describe **required** * `options.timezone` - `String` Standard timezone identification Default: `UTC` * `callback` - see all function -* **create(webhook, callback)** +* **create(webhook[, callback]) → `{Promise}`**
Create a new webhook - * `webhook` - a webhook object **required** + * `webhook` - an object of [webhook attributes](https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties) **required** * `callback` - see all function -* **update(webhook, callback)** +* **update(webhook[, callback]) → `{Promise}`**
Update an existing webhook - * `webhook` - a webhook object **required** + * `webhook` - an object of [webhook attributes](https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties) **required** * `callback` - see all function -* **delete(id, callback)** +* **delete(id[, callback]) → `{Promise}`**
Delete an existing webhook * `id` - the id of the webhook you want to delete **required** * `callback` - see all function -* **validate(options, callback)** +* **validate(options[, callback]) → `{Promise}`**
Sends an example message event batch from the Webhook API to the target URL * `options.id` - the id of the webhook you want to validate **required** * `options.message` - sample object to send to the target URL **required** * `callback` - see all function -* **getBatchStatus(options, callback)** +* **getBatchStatus(options[, callback]) → `{Promise}`**
Sends an example message event batch from the Webhook API to the target URL * `options.id` - the id of the webhook you want to get status on **required** * `options.limit` - `number` maximum number of results to return Default: `1000` * `callback` - see all function -* **getDocumentation(callback)** +* **getDocumentation([callback]) → `{Promise}`**
Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. * `callback` - see all function -* **getSamples(options, callback)** +* **getSamples(options[, callback]) → `{Promise}`**
List an example of the event data that will be posted by a Webhook for the specified events. * `options.events` - `String` event types for which to get a sample payload Defaults to all event types * `callback` - see all function +*callback is optional because all methods return a Promise. + ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); +```javascript +var SparkPost = require('sparkpost') + , client = new SparkPost('YOUR_API_KEY'); + +client.webhooks.all() + .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); + }); +// Using a callback client.webhooks.all(function(err, data) { if(err) { + console.log('Whoops! Something went wrong'); console.log(err); - return; + } else { + console.log('Congrats you can use our client library!'); + console.log(data); } - - console.log(data); }); ``` diff --git a/examples/webhooks/create_webhook.js b/examples/webhooks/create_webhook.js index f2a9ef9..59d7ec2 100644 --- a/examples/webhooks/create_webhook.js +++ b/examples/webhooks/create_webhook.js @@ -4,10 +4,10 @@ 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: [ + name: 'Test Webhook', + target: 'http://client.test.com/test-webhook', + auth_token: 'AUTH_TOKEN', + events: [ 'delivery', 'injection', 'open', @@ -15,11 +15,23 @@ var key = 'YOURAPIKEY' ] }; +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); + }); + +// Using a callback client.webhooks.create(webhook, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 index e0ae3ae..167aa76 100644 --- a/examples/webhooks/delete_webhook.js +++ b/examples/webhooks/delete_webhook.js @@ -4,11 +4,23 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.webhooks['delete']('TEST_WEBHOOK_UUID', function(err, data) { +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); + }); + +// Using a callback +client.webhooks.delete('TEST_WEBHOOK_UUID', function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/webhooks/describe_webhook.js b/examples/webhooks/describe_webhook.js index 9fc6088..779519f 100644 --- a/examples/webhooks/describe_webhook.js +++ b/examples/webhooks/describe_webhook.js @@ -4,15 +4,27 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { - id: 'TEST_WEBHOOK_UUID' - , timezone: 'America/New_York' + id: 'TEST_WEBHOOK_UUID', + timezone: 'America/New_York' }; +client.webhooks.describe(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); + }); + +// Using a callback client.webhooks.describe(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 b855967..cb27b5e 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 + id: 'TEST_WEBHOOK_UUID', + limit: 1000 }; +client.webhooks.getBatchStatus(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); + }); + +// Using a callback client.webhooks.getBatchStatus(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 5a7dfd0..902cd97 100644 --- a/examples/webhooks/getDocumentation.js +++ b/examples/webhooks/getDocumentation.js @@ -4,11 +4,23 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +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); + }); + +// Using a callback client.webhooks.getDocumentation(function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 c754330..32d2fe6 100644 --- a/examples/webhooks/getSamples.js +++ b/examples/webhooks/getSamples.js @@ -7,11 +7,23 @@ var key = 'YOURAPIKEY' events: 'bounce' }; +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); + }); + +// Using a callback client.webhooks.getSamples(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 index c5f19dd..82a8ef7 100644 --- a/examples/webhooks/get_all_webhooks.js +++ b/examples/webhooks/get_all_webhooks.js @@ -4,11 +4,23 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +client.webhooks.all() + .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); + }); + +// Using a callback client.webhooks.all(function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 index 781e8a0..734b8ed 100644 --- a/examples/webhooks/update_webhook.js +++ b/examples/webhooks/update_webhook.js @@ -4,19 +4,31 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , webhook = { - id: 'TEST_WEBHOOK_UUID' - , name: 'Renamed Test webhook' - , events: [ + id: 'TEST_WEBHOOK_UUID', + name: 'Renamed Test Webhook', + events: [ 'policy_rejection', 'delay' ] }; +client.webhooks.update(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); + }); + +// Using a callback client.webhooks.update(webhook, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); 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 index 8576d8f..dbfbd7e 100644 --- a/examples/webhooks/validate_webhook.js +++ b/examples/webhooks/validate_webhook.js @@ -4,17 +4,29 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { - id: 'TEST_WEBHOOK_UUID' - , message: { + id: 'TEST_WEBHOOK_UUID', + message: { msys: {} } }; +client.webhooks.validate(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); + }); + +// Using a callback client.webhooks.validate(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/lib/webhooks.js b/lib/webhooks.js index 34cfded..c2c314b 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,23 +1,23 @@ 'use strict'; -var api = 'webhooks' - , Promise = require('./Promise') - , toApiFormat = require('./toApiFormat'); +let _ = require('lodash') + , Promise = require('./Promise'); +const api = 'webhooks'; module.exports = function(client) { var webhooks = { all: 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; } @@ -32,11 +32,11 @@ module.exports = function(client) { } reqOpts = { - uri: api + '/' + options.id + uri: api + '/' + options.id, + qs: {} }; if (options.timezone) { - reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.timezone = options.timezone; } @@ -45,31 +45,21 @@ module.exports = function(client) { create: function(webhook, callback) { var options; - if (typeof webhook === 'function') { - callback = webhook; - webhook = null; - } - - if (!webhook) { + if (! webhook || typeof webhook === 'function') { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } options = { uri: api - , json: toApiFormat(webhook) + , json: webhook }; return client.post(options).asCallback(callback); }, update: function(webhook, callback) { - var object, options, id; - - if (typeof webhook === 'function') { - callback = webhook; - webhook = null; - } + var options; - if (!webhook) { + if (! webhook || typeof webhook === 'function') { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } @@ -77,26 +67,19 @@ module.exports = function(client) { return Promise.reject(new Error('webhook.id is required')).asCallback(callback); } - id = webhook.id; - delete webhook.id; - - object = toApiFormat(webhook); options = { - uri: api + '/' + id, - json: object + uri: api + '/' + webhook.id, + json: _.cloneDeep(webhook) }; + delete options.json.id; + return client.put(options).asCallback(callback); }, delete: function(id, callback) { var options; - if (typeof id === 'function') { - callback = id; - id = null; - } - - if (!id) { + if (!id || typeof id === 'function') { return Promise.reject(new Error('id is required')).asCallback(callback); } @@ -136,11 +119,11 @@ module.exports = function(client) { } reqOpts = { - uri: api + '/' + options.id + '/batch-status' + uri: api + '/' + options.id + '/batch-status', + qs: {} }; if (options.limit) { - reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.limit = options.limit; } @@ -154,16 +137,16 @@ module.exports = function(client) { }, 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; } diff --git a/test/spec/webhooks.spec.js b/test/spec/webhooks.spec.js index d582ccd..261a1e1 100644 --- a/test/spec/webhooks.spec.js +++ b/test/spec/webhooks.spec.js @@ -1,167 +1,138 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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(); - }); + it('should call client get method with the appropriate uri', function() { + return webhooks.all() + .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.all(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) { + it('should call client get method with the appropriate uri', function() { var options = { id: 'test' }; - webhooks.describe(options, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test'); - done(); - }); + return webhooks.describe(options) + .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.describe()).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.describe(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" + 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(webhook) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('webhooks/test'); + expect(client.put.firstCall.args[0].json).to.deep.equal(_.omit(webhook, 'id')); + }); }); - 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 webhook is missing', function() { + return expect(webhooks.update()).to.be.rejectedWith('webhook object 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.id is missing', function() { + return expect(webhooks.update({})).to.be.rejectedWith('webhook.id 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', function() { var options = { id: 'test', message: { @@ -169,100 +140,80 @@ describe('Webhooks Library', function() { } }; - webhooks.validate(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('webhooks/test/validate'); - done(); - }); + return webhooks.validate(options) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('webhooks/test/validate'); + }); }); - 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) { + it('should throw an error if message is missing', function() { 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(); - }); + return expect(webhooks.validate(options)).to.be.rejectedWith('message is required'); }); }); describe('getBatchStatus Method', function() { - it('should call client get method with the appropriate uri', function(done) { + it('should call client get method with the appropriate uri', function() { var options = { id: 'test' }; - webhooks.getBatchStatus(options, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test/batch-status'); - done(); - }); + return webhooks.getBatchStatus(options) + .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(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'}); + }); }); }); }); From 1a20aaac9a8e65ca6fab1350a16c28920434efac Mon Sep 17 00:00:00 2001 From: "Aydrian J. Howard" Date: Mon, 24 Oct 2016 15:24:09 -0400 Subject: [PATCH 20/27] eslint fixes --- lib/inboundDomains.js | 4 ++-- lib/relayWebhooks.js | 8 ++++---- lib/sparkpost.js | 6 +++--- lib/subaccounts.js | 8 ++++---- lib/templates.js | 10 +++++----- lib/transmissions.js | 4 ++-- lib/webhooks.js | 6 +++--- package.json | 2 +- 8 files changed, 24 insertions(+), 24 deletions(-) diff --git a/lib/inboundDomains.js b/lib/inboundDomains.js index 4901c89..a44485b 100644 --- a/lib/inboundDomains.js +++ b/lib/inboundDomains.js @@ -27,7 +27,7 @@ module.exports = function(client) { get: function(domain, callback) { let options; - if(!domain || typeof domain !== 'string') { + if (!domain || typeof domain !== 'string') { return Promise.reject(new Error('domain is required')).asCallback(callback); } @@ -46,7 +46,7 @@ module.exports = function(client) { create: function(createOpts, callback) { let options; - if(!createOpts || typeof createOpts !== 'object') { + if (!createOpts || typeof createOpts !== 'object') { return Promise.reject(new Error('create options are required')).asCallback(callback); } diff --git a/lib/relayWebhooks.js b/lib/relayWebhooks.js index 5a0d7af..033fef9 100644 --- a/lib/relayWebhooks.js +++ b/lib/relayWebhooks.js @@ -27,7 +27,7 @@ module.exports = function(client) { get: function(id, callback) { let options; - if(!id || typeof id !== 'string') { + if (!id || typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } @@ -46,7 +46,7 @@ module.exports = function(client) { create: function(webhook, callback) { let reqOpts; - if(!webhook || typeof webhook !== 'object') { + if (!webhook || typeof webhook !== 'object') { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } @@ -67,11 +67,11 @@ module.exports = function(client) { update: function(id, webhook, callback) { let reqOpts; - if(!id || typeof id !== 'string') { + if (!id || typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!webhook || typeof webhook !== 'object') { + if (!webhook || typeof webhook !== 'object') { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } diff --git a/lib/sparkpost.js b/lib/sparkpost.js index e068b83..1848fa1 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -14,7 +14,7 @@ defaults = { }; resolveUri = function(origin, uri) { - if(!/^http/.test(uri)) { + if (!/^http/.test(uri)) { uri = url.resolve(origin, uri); } return uri; @@ -50,7 +50,7 @@ SparkPost = function(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.'); } @@ -83,7 +83,7 @@ SparkPost.prototype.request = function(options, callback) { var baseUrl; // we need options - if(!_.isPlainObject(options)) { + if (!_.isPlainObject(options)) { throw new TypeError('options argument is required'); } diff --git a/lib/subaccounts.js b/lib/subaccounts.js index 55850d8..f4f9cf5 100644 --- a/lib/subaccounts.js +++ b/lib/subaccounts.js @@ -27,7 +27,7 @@ module.exports = function(client) { get: function(id, callback) { var options; - if(!id || typeof id !== 'string') { + if (!id || typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } @@ -46,7 +46,7 @@ module.exports = function(client) { create: function(subaccount, callback) { var reqOpts; - if(!subaccount || typeof subaccount !== 'object') { + if (!subaccount || typeof subaccount !== 'object') { return Promise.reject(new Error('subaccount object is required')).asCallback(callback); } @@ -67,11 +67,11 @@ module.exports = function(client) { update: function(id, subaccount, callback) { var reqOpts; - if(!id || typeof id !== 'string') { + if (!id || typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!subaccount || typeof subaccount !== 'object') { + if (!subaccount || typeof subaccount !== 'object') { return Promise.reject(new Error('subaccount object is required')).asCallback(callback); } diff --git a/lib/templates.js b/lib/templates.js index e29aaad..0afc637 100644 --- a/lib/templates.js +++ b/lib/templates.js @@ -16,7 +16,7 @@ module.exports = function(client) { var reqOpts; options = options || {}; - if(!options.id) { + if (!options.id) { return Promise.reject(new Error('template id is required')).asCallback(callback); } @@ -24,7 +24,7 @@ module.exports = function(client) { uri: api + '/' + options.id }; - if(options.draft) { + if (options.draft) { reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.draft = options.draft; } @@ -50,7 +50,7 @@ module.exports = function(client) { var object, reqOpts; options = options || {}; - if(!options.template) { + if (!options.template) { return Promise.reject(new Error('template object is required')).asCallback(callback); } @@ -60,7 +60,7 @@ module.exports = function(client) { , json: object }; - if(options.update_published) { + if (options.update_published) { reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.update_published = options.update_published; } @@ -88,7 +88,7 @@ module.exports = function(client) { var reqOpts; options = options || {}; - if(!options.id) { + if (!options.id) { return Promise.reject(new Error('template id is required')).asCallback(callback); } diff --git a/lib/transmissions.js b/lib/transmissions.js index 2eb350d..3c36974 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -15,7 +15,7 @@ module.exports = function(client) { send: function(transmission, callback) { var reqOpts; - if(!transmission || typeof transmission === 'function') { + if (!transmission || typeof transmission === 'function') { return Promise.reject(new Error('transmission object is required')).asCallback(callback); } @@ -35,7 +35,7 @@ module.exports = function(client) { all: function(options, callback) { var reqOpts; - if(typeof options === 'function') { + if (typeof options === 'function') { callback = options; options = {}; } diff --git a/lib/webhooks.js b/lib/webhooks.js index c2c314b..0b2f63d 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -93,11 +93,11 @@ module.exports = function(client) { var reqOpts; options = options || {}; - if(!options.id) { + if (!options.id) { return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!options.message) { + if (!options.message) { return Promise.reject(new Error('message is required')).asCallback(callback); } @@ -114,7 +114,7 @@ module.exports = function(client) { var reqOpts; options = options || {}; - if(!options.id) { + if (!options.id) { return Promise.reject(new Error('id is required')).asCallback(callback); } diff --git a/package.json b/package.json index e1094cb..d91c343 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "chai-as-promised": "^5.3.0", "coveralls": "^2.11.12", "eslint": "^3.3.1", - "eslint-config-sparkpost": "^1.0.1", + "eslint-config-sparkpost": "^1.2.0", "istanbul": "^0.4.5", "mocha": "^3.0.2", "nock": "^7.2.2", From 70cf902fbd9457750ab3c8563e70875940ba6a4c Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 25 Oct 2016 11:25:56 -0400 Subject: [PATCH 21/27] Refactored templates library (#169) * Updated templates lib and tests * Updated templates doc and examples * updated tests for payloads and cloneDeep * template refactoring for standardized verbs * Added optional options object to template update * eslint fixes * jsdoc updates * fixed webhook imports --- docs/resources/templates.md | 51 ++-- examples/templates/create.js | 36 +++ examples/templates/create_template.js | 25 -- examples/templates/delete.js | 27 ++ examples/templates/delete_template.js | 14 - examples/templates/get.js | 27 ++ examples/templates/get_all_templates.js | 14 - examples/templates/get_draft.js | 30 +++ examples/templates/get_draft_template.js | 18 -- examples/templates/get_template.js | 17 -- examples/templates/list.js | 27 ++ examples/templates/preview.js | 30 +++ examples/templates/preview_template.js | 18 -- examples/templates/update.js | 34 +++ examples/templates/update_published.js | 37 +++ .../templates/update_published_template.js | 25 -- examples/templates/update_template.js | 24 -- lib/templates.js | 134 ++++++---- lib/webhooks.js | 4 +- test/spec/templates.spec.js | 247 +++++++++--------- 20 files changed, 481 insertions(+), 358 deletions(-) create mode 100644 examples/templates/create.js delete mode 100644 examples/templates/create_template.js create mode 100644 examples/templates/delete.js delete mode 100644 examples/templates/delete_template.js create mode 100644 examples/templates/get.js delete mode 100644 examples/templates/get_all_templates.js create mode 100644 examples/templates/get_draft.js delete mode 100644 examples/templates/get_draft_template.js delete mode 100644 examples/templates/get_template.js create mode 100644 examples/templates/list.js create mode 100644 examples/templates/preview.js delete mode 100644 examples/templates/preview_template.js create mode 100644 examples/templates/update.js create mode 100644 examples/templates/update_published.js delete mode 100644 examples/templates/update_published_template.js delete mode 100644 examples/templates/update_template.js diff --git a/docs/resources/templates.md b/docs/resources/templates.md index df905da..f149aac 100644 --- a/docs/resources/templates.md +++ b/docs/resources/templates.md @@ -1,49 +1,34 @@ # Templates -This library provides easy access to the [Templates](https://www.sparkpost.com/api#/reference/templates/) Resource. +This library provides easy access to the [Templates](https://developers.sparkpost.com/api/templates) Resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **all(callback)** +* **list()**
List a summary of all templates. - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(options, callback)** - Retrieve details about a specified template by its id +* **get(id[, options])**
+ Get details about a specified template by its id * `options.id` - the id of the template you want to look up **required** * `options.draft` - specifies a draft or published template - * `callback` - see all function -* **create(options, callback)** +* **create(template)**
Create a new template - * `options.template` - a template object **required** - * `callback` - see all function -* **delete(id, callback)** + * `template` - an object of [template attributes](https://developers.sparkpost.com/api/templates#header-template-attributes) **required** +* **update(id, template[, options])**
+ Update an existing template + * `id` - the id of the template you want to update **required** + * `template` - an object of [template attributes](https://developers.sparkpost.com/api/templates#header-template-attributes) **required** + * `options.update_published` - If true, directly overwrite the existing published template. If false, create a new draft. +* **delete(id)**
Delete an existing template * `id` - the id of the template you want to delete **required** - * `callback` - see all function -* **preview(options, callback)** +* **preview(id[, options])**
Preview the most recent version of an existing template by id - * `options.id` - the id of the template you want to look up **required** - * `options.data` - Object of substitution data + * `id` - the id of the template you want to look up **required** + * `options.substitution_data` - Object of substitution data * `options.draft` - specifies a draft or published template - * `callback` - see all function ## Examples -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); - -client.templates.all(function(err, data) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` -Check out all the examples provided [here](/examples/templates). +Visit our examples section to see all of [our template resource examples](/examples/templates). diff --git a/examples/templates/create.js b/examples/templates/create.js new file mode 100644 index 0000000..f7f048a --- /dev/null +++ b/examples/templates/create.js @@ -0,0 +1,36 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , template = { + id: 'TEST_ID', + name: 'Test Template', + content: { + from: 'test@test.com', + subject: 'Test email template!', + html: 'This is a test email template!' + } + }; + +// Promise +client.templates.create(template) + .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.templates.create(template, 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/templates/create_template.js b/examples/templates/create_template.js deleted file mode 100644 index a6cb7fc..0000000 --- a/examples/templates/create_template.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - template: { - id: 'TEST_ID' - , name: 'Test Template' - , content: { - from: 'test@test.com' - , subject: 'Test email template!' - , html: 'This is a test email template!' - } - } - }; - -client.templates.create(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/delete.js b/examples/templates/delete.js new file mode 100644 index 0000000..a46f8aa --- /dev/null +++ b/examples/templates/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.templates.delete('TEST_ID') + .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.templates.delete('TEST_ID', 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/templates/delete_template.js b/examples/templates/delete_template.js deleted file mode 100644 index 93ebaa0..0000000 --- a/examples/templates/delete_template.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.templates['delete']('TEST_ID', function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/get.js b/examples/templates/get.js new file mode 100644 index 0000000..25bddaf --- /dev/null +++ b/examples/templates/get.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.templates.get('TEST_ID') + .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.templates.get('TEST_ID', 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/templates/get_all_templates.js b/examples/templates/get_all_templates.js deleted file mode 100644 index e079062..0000000 --- a/examples/templates/get_all_templates.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.templates.all(function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/get_draft.js b/examples/templates/get_draft.js new file mode 100644 index 0000000..5023f2d --- /dev/null +++ b/examples/templates/get_draft.js @@ -0,0 +1,30 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + draft: true + }; + +// Promise +client.templates.get('TEST_ID', 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.templates.get('TEST_ID', 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/templates/get_draft_template.js b/examples/templates/get_draft_template.js deleted file mode 100644 index d4f6b7c..0000000 --- a/examples/templates/get_draft_template.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'TEST_ID' - , draft: true - }; - -client.templates.find(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/get_template.js b/examples/templates/get_template.js deleted file mode 100644 index 8a64a28..0000000 --- a/examples/templates/get_template.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'TEST_ID' - }; - -client.templates.find(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/list.js b/examples/templates/list.js new file mode 100644 index 0000000..c249931 --- /dev/null +++ b/examples/templates/list.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.templates.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.templates.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/templates/preview.js b/examples/templates/preview.js new file mode 100644 index 0000000..f25059f --- /dev/null +++ b/examples/templates/preview.js @@ -0,0 +1,30 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + id: 'TEST_ID', + substitution_data: {} + }; + +client.templates.preview(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); + }); + +// Using a callback +client.templates.preview(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/templates/preview_template.js b/examples/templates/preview_template.js deleted file mode 100644 index b3b62ba..0000000 --- a/examples/templates/preview_template.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'TEST_ID' - , data: {} - }; - -client.templates.preview(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/update.js b/examples/templates/update.js new file mode 100644 index 0000000..372e326 --- /dev/null +++ b/examples/templates/update.js @@ -0,0 +1,34 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , template = { + content: { + from: 'test@test.com', + subject: 'Updated Test email template!', + html: 'This is a test email template! Updated!' + } + }; + +// Promise +client.templates.update('TEST_ID', template) + .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.templates.update('TEST_ID', template, 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/templates/update_published.js b/examples/templates/update_published.js new file mode 100644 index 0000000..ba5042b --- /dev/null +++ b/examples/templates/update_published.js @@ -0,0 +1,37 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , template = { + content: { + from: 'test@test.com', + subject: 'Updated Published Test email template!', + html: 'This is a published test email template! Updated!' + } + } + , options = { + update_published: true + }; + +// Promise +client.templates.update('TEST_ID', template, 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.templates.update('TEST_ID', template, 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/templates/update_published_template.js b/examples/templates/update_published_template.js deleted file mode 100644 index 3cbc1a8..0000000 --- a/examples/templates/update_published_template.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - template: { - id: 'TEST_ID' - , content: { - from: 'test@test.com' - , subject: 'Updated Published Test email template!' - , html: 'This is a published test email template! Updated!' - } - } - , update_published: true - }; - -client.templates.update(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/templates/update_template.js b/examples/templates/update_template.js deleted file mode 100644 index d3973c8..0000000 --- a/examples/templates/update_template.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - template: { - id: 'TEST_ID' - , content: { - from: 'test@test.com' - , subject: 'Updated Test email template!' - , html: 'This is a test email template! Updated!' - } - } - }; - -client.templates.update(options, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/lib/templates.js b/lib/templates.js index 0afc637..3e879dd 100644 --- a/lib/templates.js +++ b/lib/templates.js @@ -1,81 +1,112 @@ 'use strict'; -var api = 'templates' - , Promise = require('./Promise') - , 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 }; 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) { + if (!id) { return Promise.reject(new Error('template id is required')).asCallback(callback); } reqOpts = { - uri: api + '/' + options.id + uri: api + '/' + id + , qs: options }; - if (options.draft) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.draft = options.draft; - } - return client.get(reqOpts).asCallback(callback); }, - create: function(options, callback) { + /** + * Create a new template. + * + * @param {Object} template + * @param {RequestCb} [callback] + * @returns {Promise} + */ + create: function(template, callback) { var reqOpts; - options = options || {}; - if (!options.template) { + if (!template || typeof template !== 'object') { return Promise.reject(new Error('template object is required')).asCallback(callback); } reqOpts = { uri: api - , json: toApiFormat(options.template) + , json: template }; return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - var object, reqOpts; - 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) { + if (!id) { + return Promise.reject(new Error('template id is required')).asCallback(callback); + } + + if (!template || typeof template !== 'object') { return Promise.reject(new Error('template object is required')).asCallback(callback); } - object = toApiFormat(options.template); reqOpts = { - uri: api + '/' + object.id - , json: object + uri: api + '/' + id + , json: template + , qs: options }; - if (options.update_published) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.update_published = options.update_published; - } - 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 (typeof id === 'function') { - callback = id; - id = null; - } - - if (!id) { + if (!id || typeof id !== 'string') { return Promise.reject(new Error('template id is required')).asCallback(callback); } @@ -84,29 +115,40 @@ module.exports = function(client) { }; 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) { + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (!id) { return Promise.reject(new Error('template id is required')).asCallback(callback); } reqOpts = { - uri: api + '/' + options.id + '/preview' - , json: { - substitution_data: options.data - } + uri: api + '/' + id + '/preview' + , json: _.cloneDeep(options) + , qs: {} }; - if (options.draft) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.draft = options.draft; + if (reqOpts.json.draft) { + reqOpts.qs.draft = reqOpts.json.draft; + delete reqOpts.json.draft; } return client.post(reqOpts).asCallback(callback); } }; - - return templates; }; diff --git a/lib/webhooks.js b/lib/webhooks.js index 0b2f63d..d5a9b42 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,8 +1,8 @@ 'use strict'; -let _ = require('lodash') - , Promise = require('./Promise'); const api = 'webhooks'; +const Promise = require('./Promise'); +const _ = require('lodash'); module.exports = function(client) { var webhooks = { diff --git a/test/spec/templates.spec.js b/test/spec/templates.spec.js index 9161cea..a0760bc 100644 --- a/test/spec/templates.spec.js +++ b/test/spec/templates.spec.js @@ -1,180 +1,183 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , Promise = require('../../lib/Promise'); + , 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().returns(Promise.resolve({})), - post: sinon.stub().returns(Promise.resolve({})), - put: sinon.stub().returns(Promise.resolve({})), - delete: sinon.stub().returns(Promise.resolve({})) + 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}); + }); }); }); }); From 93782cb576543efb5d3d097708085212c98514a6 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 25 Oct 2016 16:19:37 -0400 Subject: [PATCH 22/27] Removed toApiFormat (#181) --- lib/toApiFormat.js | 52 ---------- package.json | 5 +- test/spec/sparkpost.spec.js | 5 +- test/spec/toApiFormat.spec.js | 184 ---------------------------------- 4 files changed, 4 insertions(+), 242 deletions(-) delete mode 100644 lib/toApiFormat.js delete mode 100644 test/spec/toApiFormat.spec.js diff --git a/lib/toApiFormat.js b/lib/toApiFormat.js deleted file mode 100644 index b899a5b..0000000 --- a/lib/toApiFormat.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; -var _ = require('lodash') - , pointer = require('json-pointer') - , excludeList = [ - '/substitution_data', - '/tags', - '/metadata', - '/attributes', - '/headers', - '/content/email_rfc822' - ]; - -function snakedKeyClone(source) { - var target; - - if (!_.isObject(source)) { - return source; - } - - 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 = {}, target; - - // 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 - 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/package.json b/package.json index d91c343..f4bd59e 100644 --- a/package.json +++ b/package.json @@ -25,19 +25,18 @@ "homepage": "https://github.com/SparkPost/node-sparkpost", "devDependencies": { "chai": "^3.5.0", - "chai-as-promised": "^5.3.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": "^7.2.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.74.0" } diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 78f4c84..7ada0d6 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -108,16 +108,15 @@ describe('SparkPost Library', function() { }); it('should return an error when the request fails', function(done) { - // simulate a timeout + // simulate a bad multipart to make request error nock('https://api.sparkpost.com') .get('/api/v1/get/test/fail') - .delayConnection(500) .reply(200); var options = { method: 'GET' , uri: 'get/test/fail' - , timeout: 100 + , multipart: [ {} ] }; client.request(options, function(err, data) { 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(); - }); -}); From 21bd3321ce479d0a96a5945bb766d103e6b0e9c4 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Thu, 27 Oct 2016 11:47:05 -0400 Subject: [PATCH 23/27] Standardized action verbs for Webhooks (#183) * Updated webhooks lib and tests * Updated webhooks doc and examples * updated tests for payloads and cloneDeep * validates required parameters and jsdocs to webhooks wrapper * update docs for webhooks * updated docs, tests, and examples * eslint fixes * fix merge conflicts --- docs/resources/webhooks.md | 96 +++++------- .../webhooks/{create_webhook.js => create.js} | 3 +- .../webhooks/{delete_webhook.js => delete.js} | 3 +- .../webhooks/{describe_webhook.js => get.js} | 8 +- examples/webhooks/getBatchStatus.js | 8 +- examples/webhooks/getDocumentation.js | 3 +- examples/webhooks/getSamples.js | 3 +- .../webhooks/{get_all_webhooks.js => list.js} | 7 +- .../webhooks/{update_webhook.js => update.js} | 8 +- .../{validate_webhook.js => validate.js} | 8 +- lib/webhooks.js | 145 ++++++++++++++---- test/spec/webhooks.spec.js | 53 +++---- 12 files changed, 198 insertions(+), 147 deletions(-) rename examples/webhooks/{create_webhook.js => create.js} (97%) rename examples/webhooks/{delete_webhook.js => delete.js} (96%) rename examples/webhooks/{describe_webhook.js => get.js} (79%) rename examples/webhooks/{get_all_webhooks.js => list.js} (84%) rename examples/webhooks/{update_webhook.js => update.js} (80%) rename examples/webhooks/{validate_webhook.js => validate.js} (78%) diff --git a/docs/resources/webhooks.md b/docs/resources/webhooks.md index 120a216..41d8dd6 100644 --- a/docs/resources/webhooks.md +++ b/docs/resources/webhooks.md @@ -2,56 +2,21 @@ This library provides easy access to the [Webhooks](https://developers.sparkpost.com/api/webhooks) Resource. -## Methods -* **all([options, callback]) → `{Promise}`**
- List currently extant webhooks. - * `options.timezone` - `String` Standard timezone identification Default: `UTC` - * `callback` - executed after task is completed if provided* - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **describe(options[, callback]) → `{Promise}`**
- Retrieve details about a specified webhook by its id - * `options.id` - the id of the webhook you want to describe **required** - * `options.timezone` - `String` Standard timezone identification Default: `UTC` - * `callback` - see all function -* **create(webhook[, callback]) → `{Promise}`**
- Create a new webhook - * `webhook` - an object of [webhook attributes](https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties) **required** - * `callback` - see all function -* **update(webhook[, callback]) → `{Promise}`**
- Update an existing webhook - * `webhook` - an object of [webhook attributes](https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties) **required** - * `callback` - see all function -* **delete(id[, callback]) → `{Promise}`**
- Delete an existing webhook - * `id` - the id of the webhook you want to delete **required** - * `callback` - see all function -* **validate(options[, callback]) → `{Promise}`**
- Sends an example message event batch from the Webhook API to the target URL - * `options.id` - the id of the webhook you want to validate **required** - * `options.message` - sample object to send to the target URL **required** - * `callback` - see all function -* **getBatchStatus(options[, callback]) → `{Promise}`**
- Sends an example message event batch from the Webhook API to the target URL - * `options.id` - the id of the webhook you want to get status on **required** - * `options.limit` - `number` maximum number of results to return Default: `1000` - * `callback` - see all function -* **getDocumentation([callback]) → `{Promise}`**
- Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. - * `callback` - see all function -* **getSamples(options[, callback]) → `{Promise}`**
- List an example of the event data that will be posted by a Webhook for the specified events. - * `options.events` - `String` event types for which to get a sample payload Defaults to all event types - * `callback` - see all function +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* -*callback is optional because all methods return a Promise. +## Methods +* **list([options])**
+ Lists all webhooks. + * `options.timezone` - the timezone to use for the `last_successful` and `last_failure` properties | Default: `UTC` -## Examples +* **get(id[, options])**
+ Get a single webhook by ID. + * `id` - the id of the webhook to get **required** + * `options.timezone` - the timezone to use for the `last_successful` and `last_failure` properties | Default: `UTC` -```javascript -var SparkPost = require('sparkpost') - , client = new SparkPost('YOUR_API_KEY'); +* **create(webhook)**
+ Create a new webhook. + * `webhook` - a hash of [webhook attributes](https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties) **required** client.webhooks.all() .then(data => { @@ -63,17 +28,30 @@ client.webhooks.all() console.log(err); }); -// Using a callback -client.webhooks.all(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); - } -}); +* **update(id, webhook)**
+ Update an existing webhook. + * `id` - the id of the webhook to update **required** + * `webhook` - a hash of [webhook attributes](https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties) **required** +* **delete(id)**
+ Delete an existing webhook. + * `id` - the id of the webhook to delete **required** + +* **validate(id, options)**
+ Sends an example message event batch from the Webhook API to the target URL. + * `id` - the id of the webhook to validate **required** + * `options.message` - the message (payload) to send to the webhook consumer **required** + +* **getBatchStatus(id[, options])**
+ Gets recent status information about a webhook. + * `id` - the id of the webhook **required** + * `options.limit` - maximum number of results to return | Default: `1000` + +* **getDocumentation()**
+ Lists descriptions of the events, event types, and event fields that could be included in a webhooks post to your target URL. + +* **getSamples(options)**
+ Lists examples of the event data that will be posted to a webhook consumer. + * `options.events` - [event types](https://support.sparkpost.com/customer/portal/articles/1976204) for which to get a sample payload | Default: all event types returned -``` -Check out all the examples provided [here](/examples/webhooks). +Visit our examples section to see all of [our webhooks resource examples](/examples/webhooks). diff --git a/examples/webhooks/create_webhook.js b/examples/webhooks/create.js similarity index 97% rename from examples/webhooks/create_webhook.js rename to examples/webhooks/create.js index 59d7ec2..97b532c 100644 --- a/examples/webhooks/create_webhook.js +++ b/examples/webhooks/create.js @@ -15,6 +15,7 @@ var key = 'YOURAPIKEY' ] }; +// Promise client.webhooks.create(webhook) .then(data => { console.log('Congrats you can use our client library!'); @@ -25,7 +26,7 @@ client.webhooks.create(webhook) console.log(err); }); -// Using a callback +// Callback client.webhooks.create(webhook, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/webhooks/delete_webhook.js b/examples/webhooks/delete.js similarity index 96% rename from examples/webhooks/delete_webhook.js rename to examples/webhooks/delete.js index 167aa76..725e342 100644 --- a/examples/webhooks/delete_webhook.js +++ b/examples/webhooks/delete.js @@ -4,6 +4,7 @@ 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!'); @@ -14,7 +15,7 @@ client.webhooks.delete('TEST_WEBHOOK_UUID') console.log(err); }); -// Using a callback +// Callback client.webhooks.delete('TEST_WEBHOOK_UUID', function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/webhooks/describe_webhook.js b/examples/webhooks/get.js similarity index 79% rename from examples/webhooks/describe_webhook.js rename to examples/webhooks/get.js index 779519f..57cdbb6 100644 --- a/examples/webhooks/describe_webhook.js +++ b/examples/webhooks/get.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { - id: 'TEST_WEBHOOK_UUID', timezone: 'America/New_York' }; -client.webhooks.describe(options) +// Promise +client.webhooks.get('TEST_WEBHOOK_UUID', options) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -18,8 +18,8 @@ client.webhooks.describe(options) console.log(err); }); -// Using a callback -client.webhooks.describe(options, function(err, data) { +// Callback +client.webhooks.get('TEST_WEBHOOK_UUID', options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/webhooks/getBatchStatus.js b/examples/webhooks/getBatchStatus.js index cb27b5e..2826764 100644 --- a/examples/webhooks/getBatchStatus.js +++ b/examples/webhooks/getBatchStatus.js @@ -4,11 +4,11 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { - id: 'TEST_WEBHOOK_UUID', limit: 1000 }; -client.webhooks.getBatchStatus(options) +// Promise +client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', options) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -18,8 +18,8 @@ client.webhooks.getBatchStatus(options) console.log(err); }); -// Using a callback -client.webhooks.getBatchStatus(options, function(err, data) { +// Callback +client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/webhooks/getDocumentation.js b/examples/webhooks/getDocumentation.js index 902cd97..8319814 100644 --- a/examples/webhooks/getDocumentation.js +++ b/examples/webhooks/getDocumentation.js @@ -4,6 +4,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +// Promise client.webhooks.getDocumentation() .then(data => { console.log('Congrats you can use our client library!'); @@ -14,7 +15,7 @@ client.webhooks.getDocumentation() console.log(err); }); -// Using a callback +// Callback client.webhooks.getDocumentation(function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/webhooks/getSamples.js b/examples/webhooks/getSamples.js index 32d2fe6..3843865 100644 --- a/examples/webhooks/getSamples.js +++ b/examples/webhooks/getSamples.js @@ -7,6 +7,7 @@ var key = 'YOURAPIKEY' events: 'bounce' }; +// Promise client.webhooks.getSamples(options) .then(data => { console.log('Congrats you can use our client library!'); @@ -17,7 +18,7 @@ client.webhooks.getSamples(options) console.log(err); }); -// Using a callback +// Callback client.webhooks.getSamples(options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/webhooks/get_all_webhooks.js b/examples/webhooks/list.js similarity index 84% rename from examples/webhooks/get_all_webhooks.js rename to examples/webhooks/list.js index 82a8ef7..10f4756 100644 --- a/examples/webhooks/get_all_webhooks.js +++ b/examples/webhooks/list.js @@ -4,7 +4,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.webhooks.all() +// Promise +client.webhooks.list() .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -14,8 +15,8 @@ client.webhooks.all() console.log(err); }); -// Using a callback -client.webhooks.all(function(err, data) { +// Callback +client.webhooks.list(function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/webhooks/update_webhook.js b/examples/webhooks/update.js similarity index 80% rename from examples/webhooks/update_webhook.js rename to examples/webhooks/update.js index 734b8ed..8c33443 100644 --- a/examples/webhooks/update_webhook.js +++ b/examples/webhooks/update.js @@ -4,7 +4,6 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , webhook = { - id: 'TEST_WEBHOOK_UUID', name: 'Renamed Test Webhook', events: [ 'policy_rejection', @@ -12,7 +11,8 @@ var key = 'YOURAPIKEY' ] }; -client.webhooks.update(webhook) +// Promise +client.webhooks.update('TEST_WEBHOOK_UUID', webhook) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -22,8 +22,8 @@ client.webhooks.update(webhook) console.log(err); }); -// Using a callback -client.webhooks.update(webhook, function(err, data) { +// Callback +client.webhooks.update('TEST_WEBHOOK_UUID', webhook, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/webhooks/validate_webhook.js b/examples/webhooks/validate.js similarity index 78% rename from examples/webhooks/validate_webhook.js rename to examples/webhooks/validate.js index dbfbd7e..d1a312f 100644 --- a/examples/webhooks/validate_webhook.js +++ b/examples/webhooks/validate.js @@ -4,13 +4,13 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { - id: 'TEST_WEBHOOK_UUID', message: { msys: {} } }; -client.webhooks.validate(options) +// Promise +client.webhooks.validate('TEST_WEBHOOK_UUID', options) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -20,8 +20,8 @@ client.webhooks.validate(options) console.log(err); }); -// Using a callback -client.webhooks.validate(options, function(err, data) { +// Callback +client.webhooks.validate('TEST_WEBHOOK_UUID', options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/lib/webhooks.js b/lib/webhooks.js index d5a9b42..76dd824 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,12 +1,20 @@ 'use strict'; -const api = 'webhooks'; const Promise = require('./Promise'); -const _ = require('lodash'); +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, qs: {} @@ -23,16 +31,30 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, - describe: function(options, callback) { + + /** + * 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; - options = options || {}; - if (!options.id) { + if (!options || typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } reqOpts = { - uri: api + '/' + options.id, + uri: api + '/' + id, qs: {} }; @@ -42,40 +64,64 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, + + /** + * 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') { + if (!webhook || typeof webhook === 'function') { return Promise.reject(new Error('webhook object is required')).asCallback(callback); } options = { - uri: api - , json: webhook + uri: api, + json: webhook }; return client.post(options).asCallback(callback); }, - update: function(webhook, callback) { - var options; - if (! webhook || typeof webhook === 'function') { - return Promise.reject(new Error('webhook object is required')).asCallback(callback); + /** + * 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) { - return Promise.reject(new Error('webhook.id is required')).asCallback(callback); + if (!webhook || typeof webhook === 'function') { + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } options = { - uri: api + '/' + webhook.id, - json: _.cloneDeep(webhook) + uri: api + '/' + id, + json: webhook }; delete options.json.id; return client.put(options).asCallback(callback); }, + + /** + * 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; @@ -89,37 +135,60 @@ module.exports = function(client) { return client.delete(options).asCallback(callback); }, - validate: function(options, callback) { + + /** + * 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; - options = options || {}; - if (!options.id) { + if (typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } - if (!options.message) { + if (!options || typeof options === 'function' || !options.message) { return Promise.reject(new Error('message is required')).asCallback(callback); } reqOpts = { - uri: api + '/' + options.id + '/validate' - , json: { + uri: api + '/' + id + '/validate', + json: { message: options.message } }; return client.post(reqOpts).asCallback(callback); }, - getBatchStatus: function(options, callback) { + + /** + * 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; - options = options || {}; - if (!options.id) { + if (!options || typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof id !== 'string') { return Promise.reject(new Error('id is required')).asCallback(callback); } reqOpts = { - uri: api + '/' + options.id + '/batch-status', + uri: api + '/' + id + '/batch-status', qs: {} }; @@ -129,12 +198,28 @@ module.exports = function(client) { 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' }; return client.get(reqOpts).asCallback(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', @@ -153,6 +238,4 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); } }; - - return webhooks; }; diff --git a/test/spec/webhooks.spec.js b/test/spec/webhooks.spec.js index 261a1e1..2f79d49 100644 --- a/test/spec/webhooks.spec.js +++ b/test/spec/webhooks.spec.js @@ -24,9 +24,9 @@ describe('Webhooks Library', function() { webhooks = require('../../lib/webhooks')(client); }); - describe('all Method', function() { + describe('list Method', function() { it('should call client get method with the appropriate uri', function() { - return webhooks.all() + return webhooks.list() .then(function() { expect(client.get.firstCall.args[0].uri).to.equal('webhooks'); }); @@ -37,36 +37,31 @@ describe('Webhooks Library', function() { timezone: 'America/New_York' }; - return webhooks.all(options) + return webhooks.list(options) .then(function() { expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'}); }); }); }); - describe('describe Method', function() { + describe('get Method', function() { it('should call client get method with the appropriate uri', function() { - var options = { - id: 'test' - }; - - return webhooks.describe(options) + 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() { - return expect(webhooks.describe()).to.be.rejectedWith('id is required'); + return expect(webhooks.get()).to.be.rejectedWith('id is required'); }); it('should allow timezone to be set in options', function() { var options = { - id: 'test', timezone: 'America/New_York' }; - return webhooks.describe(options) + return webhooks.get('test', options) .then(function() { expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'}); }); @@ -96,25 +91,24 @@ describe('Webhooks Library', function() { describe('update Method', function() { it('should call client put method with the appropriate uri', function() { var webhook = { - id: 'test', name: 'Renamed webhook', events: ['rejection', 'delay'], auth_type: 'none' }; - return webhooks.update(webhook) + 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(_.omit(webhook, 'id')); + expect(client.put.firstCall.args[0].json).to.deep.equal(webhook); }); }); - it('should throw an error if webhook is missing', function() { - return expect(webhooks.update()).to.be.rejectedWith('webhook object is required'); + 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() { - return expect(webhooks.update({})).to.be.rejectedWith('webhook.id is required'); + it('should throw an error if webhook is missing', function() { + return expect(webhooks.update('test')).to.be.rejectedWith('webhook object is required'); }); }); @@ -132,17 +126,17 @@ describe('Webhooks Library', function() { }); describe('validate Method', function() { - it('should call client post method with the appropriate uri', function() { + it('should call client post method with the appropriate uri and payload', function() { var options = { - id: 'test', message: { msys: {} } }; - return webhooks.validate(options) + 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); }); }); @@ -151,21 +145,13 @@ describe('Webhooks Library', function() { }); it('should throw an error if message is missing', function() { - var options = { - id: 'test' - }; - - return expect(webhooks.validate(options)).to.be.rejectedWith('message is required'); + 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() { - var options = { - id: 'test' - }; - - return webhooks.getBatchStatus(options) + return webhooks.getBatchStatus('test') .then(function() { expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test/batch-status'); }); @@ -177,11 +163,10 @@ describe('Webhooks Library', function() { it('should allow limit to be set in options', function() { var options = { - id: 'test', limit: 1000 }; - return webhooks.getBatchStatus(options) + return webhooks.getBatchStatus('test', options) .then(function() { expect(client.get.firstCall.args[0].qs).to.deep.equal({limit: 1000}); }); From 65572880d26b9493417268065ceee1984896dbcf Mon Sep 17 00:00:00 2001 From: Aydrian Date: Tue, 1 Nov 2016 14:55:10 -0400 Subject: [PATCH 24/27] Standardized action verbs on remaining libraries (#184) * Removed toApiFormat * Updated subaccount examples * Refactored transmissions library * Refactered Message Events resource * fixes based on feedback * Added back code to handle arrays for messageEvents * Fixed messageEvents examples --- docs/resources/messageEvents.md | 50 ++----------- docs/resources/transmissions.md | 58 +++------------ examples/messageEvents/all_messageEvents.js | 15 ---- .../messageEvents/search_campaignClicks.js | 22 ++++-- examples/messageEvents/search_default.js | 29 ++++++++ .../messageEvents/search_messageEvents.js | 30 +++++--- .../{create_subaccount.js => create.js} | 3 +- .../subaccounts/{get_subaccount.js => get.js} | 3 +- .../{list_subaccounts.js => list.js} | 3 +- .../{update_subaccount.js => update.js} | 3 +- .../{get_transmission.js => get.js} | 7 +- .../{get_all_transmissions.js => list.js} | 7 +- ...ons_by_campaign.js => list_by_campaign.js} | 4 +- ...ons_by_template.js => list_by_template.js} | 7 +- ...ssion_all_fields.js => send_all_fields.js} | 7 +- .../{mime_parts.js => send_mime_parts.js} | 3 +- .../{rfc822.js => send_rfc822.js} | 3 +- ... send_stored_recipients_inline_content.js} | 3 +- ... send_stored_recipients_stored_content.js} | 7 +- ...mplate_send.js => send_stored_template.js} | 11 +-- ...nsmission_with_bcc.js => send_with_bcc.js} | 3 +- ...ransmission_with_cc.js => send_with_cc.js} | 9 +-- lib/messageEvents.js | 35 +++++---- lib/transmissions.js | 71 ++++++++++++------- test/spec/messageEvents.spec.js | 44 ++++++------ test/spec/transmissions.spec.js | 36 ++++++---- 26 files changed, 243 insertions(+), 230 deletions(-) delete mode 100644 examples/messageEvents/all_messageEvents.js create mode 100644 examples/messageEvents/search_default.js rename examples/subaccounts/{create_subaccount.js => create.js} (97%) rename examples/subaccounts/{get_subaccount.js => get.js} (96%) rename examples/subaccounts/{list_subaccounts.js => list.js} (96%) rename examples/subaccounts/{update_subaccount.js => update.js} (96%) rename examples/transmissions/{get_transmission.js => get.js} (77%) rename examples/transmissions/{get_all_transmissions.js => list.js} (80%) rename examples/transmissions/{get_transmissions_by_campaign.js => list_by_campaign.js} (86%) rename examples/transmissions/{get_transmissions_by_template.js => list_by_template.js} (82%) rename examples/transmissions/{send_transmission_all_fields.js => send_all_fields.js} (95%) rename examples/transmissions/{mime_parts.js => send_mime_parts.js} (97%) rename examples/transmissions/{rfc822.js => send_rfc822.js} (97%) rename examples/transmissions/{stored_recipients_inline_content.js => send_stored_recipients_inline_content.js} (97%) rename examples/transmissions/{stored_recipients_stored_content.js => send_stored_recipients_stored_content.js} (90%) rename examples/transmissions/{stored_template_send.js => send_stored_template.js} (79%) rename examples/transmissions/{send_transmission_with_bcc.js => send_with_bcc.js} (98%) rename examples/transmissions/{send_transmission_with_cc.js => send_with_cc.js} (90%) diff --git a/docs/resources/messageEvents.md b/docs/resources/messageEvents.md index 6ef8bef..f61cf06 100644 --- a/docs/resources/messageEvents.md +++ b/docs/resources/messageEvents.md @@ -1,28 +1,17 @@ # Message Events -This library provides easy access to the [Message Events](https://www.sparkpost.com/api#/reference/message-events/) resource. +This library provides easy access to the [Message Events](https://developers.sparkpost.com/api/message-events) resource. + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* ## Methods -* **search(params, callback)** +* **search([params, callback])**
Search for message events using the given parameters (NOTE: all params are optional): - * `params.bounce_classes` - list of [bounce classes](https://support.sparkpost.com/customer/portal/articles/1929896) - * `params.campaign_ids` - campaign IDs - * `params.events` - event types - * `params.friendly_froms` - 'friendly' from addressess - * `params.from` - time lower bound (see below for date/time format details) - * `params.message_ids` - message IDs - * `params.page` - results page number - * `params.per_page` - number of results per page - * `params.reason` - bounce reason with '%' wildcards (see below for example) - * `params.recipients` - recipient email addresses - * `params.template_ids` - template IDs - * `params.timezone` - timezone for `from` and `to` params ([reference](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)) - * `params.to` - time upper bound (see below for date/time format details) - * `params.transmission_ids` - transmission IDs + * `params` - a hash of [Message Events URI Parameters](https://developers.sparkpost.com/api/message-events.html#message-events-message-events-get) ## Date/Time Parameter Format -The `from` and `to` search parameters accept datestamps of the form: +The `from` and `to` search parameters accept date stamps of the form: `YYYY-MM-DDTHH:MM` @@ -32,29 +21,4 @@ Note: timestamps are expressed in the timezone specified by the `timezone` param ## Examples -This example code retrieves up to 5 'invalid recipient' bounce events from the first 2 days of 2016. - -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); -var searchParams = { - from: '2016-01-01T00:00', - to: '2016-01-02T23:59', - page: 1, - per_page: 5, - events: ['bounce', 'out_of_band'], - bounce_classes: [10] -}; - -client.messageEvents.search(searchParams, function(err, res) { - if(err) { - console.log(err); - return; - } - - console.log(data); -}); - -``` - -Check out all the examples provided [here](/examples/messageEvents). +Visit our examples section to see all of [our message events resource examples](/examples/messageEvents). diff --git a/docs/resources/transmissions.md b/docs/resources/transmissions.md index b2fa235..4e0ed52 100644 --- a/docs/resources/transmissions.md +++ b/docs/resources/transmissions.md @@ -2,66 +2,24 @@ This library provides easy access to the [Transmissions](https://developers.sparkpost.com/api/transmissions) Resource. +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* + ## Methods -* **all(options[, callback]) → `{Promise}`**
+* **list(options[, callback])**
List an overview of all transmissions in the account * `options.campaign_id` - id of the campaign used by the transmission * `options.template_id` - id of the template used by the transmission - * `callback` - executed after task is completed if provided* - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - results returned by the api -* **find(id[, callback]) → `{Promise}`**
+* **get(id[, callback])**
Retrieve the details about a transmission by its ID * `id` - id of the transmission you want to look up **required** - * `callback` - see all function -* **send(transmission[, callback]) → `{Promise}`**
+* **send(transmission[, options, callback])**
Sends a message by creating a new transmission * `transmission` - an object of [transmission attributes](https://developers.sparkpost.com/api/transmissions#header-transmission-attributes) - * `transmission.num_rcpt_errors` - maximum number of recipient errors returned - * `callback` - see all function - -*callback is optional because all methods return a Promise. - -## Getting Started: Your First Mailing - -```javascript -var SparkPost = require('sparkpost') - , client = new SparkPost('YOUR API KEY') - , options = { - campaign_id: 'first-mailing', - content: { - from: 'you@your-company.com', - subject: 'First SDK Mailing', - html: '

Congratulations, {{name}}!

You just sent your very first mailing!

', - text: 'Congratulations, {{name}}!! You just sent your very first mailing!' - }, - substitution_data: {name: 'YOUR FIRST NAME'}, - recipients: [{ address: { name: 'YOUR FULL NAME', email: 'YOUR EMAIL ADDRESS' } }] - }; + * `options.num_rcpt_errors` - maximum number of recipient errors returned -client.transmissions.send(options) - .then(data => { - console.log('Woohoo! You just sent your first mailing!'); - console.log(data); - }) - .catch(err => { - console.log('Whoops! Something went wrong'); - console.log(err); - }); +## Examples -// Using a callback -client.transmissions.send(options, function(err, data) { - if (err) { - console.log('Whoops! Something went wrong'); - console.log(err); - } else { - console.log('Woohoo! You just sent your first mailing!'); - console.log(data); - } -}); -``` -Check out all the examples provided [here](/examples/transmissions). +Visit our examples section to see all of [our transmissions resource examples](/examples/transmissions). ## Tips and Tricks * If you specify a stored recipient list and inline recipients in a Transmission, you will receive an error. diff --git a/examples/messageEvents/all_messageEvents.js b/examples/messageEvents/all_messageEvents.js deleted file mode 100644 index 113158c..0000000 --- a/examples/messageEvents/all_messageEvents.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.messageEvents.search({}, function(err, data) { - if (err) { - console.log(err); - } else { - console.log(data); - console.log('Congrats you can use our client library!'); - } -}); - diff --git a/examples/messageEvents/search_campaignClicks.js b/examples/messageEvents/search_campaignClicks.js index 49b74bd..6b15cde 100644 --- a/examples/messageEvents/search_campaignClicks.js +++ b/examples/messageEvents/search_campaignClicks.js @@ -4,16 +4,28 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , searchParams = { - events: 'click', - campaign_ids: 'monday_mailshot' - }; + events: 'click', + campaign_ids: 'monday_mailshot' + }; +// Promise +client.messageEvents.search(searchParams) + .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.messageEvents.search(searchParams, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); - diff --git a/examples/messageEvents/search_default.js b/examples/messageEvents/search_default.js new file mode 100644 index 0000000..9339cbb --- /dev/null +++ b/examples/messageEvents/search_default.js @@ -0,0 +1,29 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Returns 1000 events for the last hour + +// Promise +client.messageEvents.search({}) + .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.messageEvents.search({}, 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/messageEvents/search_messageEvents.js b/examples/messageEvents/search_messageEvents.js index 9b2250a..ce50e57 100644 --- a/examples/messageEvents/search_messageEvents.js +++ b/examples/messageEvents/search_messageEvents.js @@ -4,20 +4,32 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , searchParams = { - from: '2016-01-01T00:00', - to: '2016-01-02T23:59', - page: 1, - per_page: 5, - events: ['bounce', 'out_of_band'], - bounce_classes: [10] - }; + from: '2016-01-01T00:00', + to: '2016-01-02T23:59', + page: 1, + per_page: 5, + events: ['bounce', 'out_of_band'], + bounce_classes: [10] + }; +// Promise +client.messageEvents.search(searchParams) + .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.messageEvents.search(searchParams, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(data); console.log('Congrats you can use our client library!'); + console.log(data); } }); - diff --git a/examples/subaccounts/create_subaccount.js b/examples/subaccounts/create.js similarity index 97% rename from examples/subaccounts/create_subaccount.js rename to examples/subaccounts/create.js index 3c94f4d..1374705 100644 --- a/examples/subaccounts/create_subaccount.js +++ b/examples/subaccounts/create.js @@ -12,6 +12,7 @@ var key = 'YOURAPIKEY' ] }; +// Promise client.subaccounts.create(subaccount) .then(data => { console.log('Congrats you can use our client library!'); @@ -22,7 +23,7 @@ client.subaccounts.create(subaccount) console.log(err); }); -// Using a callback +// Callback client.subaccounts.create(subaccount, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/subaccounts/get_subaccount.js b/examples/subaccounts/get.js similarity index 96% rename from examples/subaccounts/get_subaccount.js rename to examples/subaccounts/get.js index 238075c..9f0e45a 100644 --- a/examples/subaccounts/get_subaccount.js +++ b/examples/subaccounts/get.js @@ -4,6 +4,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +// Promise client.subaccounts.get('123') .then(data => { console.log('Congrats you can use our client library!'); @@ -14,7 +15,7 @@ client.subaccounts.get('123') console.log(err); }); -// Using a callback +// Callback client.subaccounts.get('123', function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/subaccounts/list_subaccounts.js b/examples/subaccounts/list.js similarity index 96% rename from examples/subaccounts/list_subaccounts.js rename to examples/subaccounts/list.js index 78e5be7..877bdd1 100644 --- a/examples/subaccounts/list_subaccounts.js +++ b/examples/subaccounts/list.js @@ -4,6 +4,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); +// Promise client.subaccounts.list() .then(data => { console.log('Congrats you can use our client library!'); @@ -14,7 +15,7 @@ client.subaccounts.list() console.log(err); }); -// Using a callback +// Callback client.subaccounts.list(function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/subaccounts/update_subaccount.js b/examples/subaccounts/update.js similarity index 96% rename from examples/subaccounts/update_subaccount.js rename to examples/subaccounts/update.js index 96309a4..565a093 100644 --- a/examples/subaccounts/update_subaccount.js +++ b/examples/subaccounts/update.js @@ -8,6 +8,7 @@ var key = 'YOURAPIKEY' status: 'suspended' }; +// Promise client.subaccounts.update('123', subaccount) .then(data => { console.log('Congrats you can use our client library!'); @@ -18,7 +19,7 @@ client.subaccounts.update('123', subaccount) console.log(err); }); -// Using a callback +// Callback client.subaccounts.update('123', subaccount, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/get_transmission.js b/examples/transmissions/get.js similarity index 77% rename from examples/transmissions/get_transmission.js rename to examples/transmissions/get.js index e39fa12..8aabe7c 100644 --- a/examples/transmissions/get_transmission.js +++ b/examples/transmissions/get.js @@ -4,7 +4,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.transmissions.find('YOUR-TRANsMISSION-KEY') +// Promise +client.transmissions.get('YOUR-TRANSMISSION-KEY') .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -14,8 +15,8 @@ client.transmissions.find('YOUR-TRANsMISSION-KEY') console.log(err); }); -// Using a callback -client.transmissions.find('YOUR-TRANSMISSION-KEY', function(err, data) { +// Callback +client.transmissions.get('YOUR-TRANSMISSION-KEY', function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/transmissions/get_all_transmissions.js b/examples/transmissions/list.js similarity index 80% rename from examples/transmissions/get_all_transmissions.js rename to examples/transmissions/list.js index 8d3be4b..4ddeaeb 100644 --- a/examples/transmissions/get_all_transmissions.js +++ b/examples/transmissions/list.js @@ -4,7 +4,8 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.transmissions.all() +// Promise +client.transmissions.list() .then(data => { console.log(data); console.log('Congrats you can use our client library!'); @@ -13,8 +14,8 @@ client.transmissions.all() console.log(err); }); -// Using a callback -client.transmissions.all(function(err, data) { +// Callback +client.transmissions.list(function(err, data) { if (err) { console.log(err); } else { diff --git a/examples/transmissions/get_transmissions_by_campaign.js b/examples/transmissions/list_by_campaign.js similarity index 86% rename from examples/transmissions/get_transmissions_by_campaign.js rename to examples/transmissions/list_by_campaign.js index 47d0ed1..bd50150 100644 --- a/examples/transmissions/get_transmissions_by_campaign.js +++ b/examples/transmissions/list_by_campaign.js @@ -7,7 +7,7 @@ var key = 'YOURAPIKEY' campaign_id: 'my_campaign' }; -client.transmissions.all(options) +client.transmissions.list(options) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -18,7 +18,7 @@ client.transmissions.all(options) }); // Using a callback -client.transmissions.all(options, function(err, data) { +client.transmissions.list(options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/transmissions/get_transmissions_by_template.js b/examples/transmissions/list_by_template.js similarity index 82% rename from examples/transmissions/get_transmissions_by_template.js rename to examples/transmissions/list_by_template.js index bfa6a5b..28ff2ce 100644 --- a/examples/transmissions/get_transmissions_by_template.js +++ b/examples/transmissions/list_by_template.js @@ -7,7 +7,8 @@ var key = 'YOURAPIKEY' template_id: 'my_template' }; -client.transmissions.all(options) +// Promise +client.transmissions.list(options) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -17,8 +18,8 @@ client.transmissions.all(options) console.log(err); }); -// Using a callback -client.transmissions.all(options, function(err, data) { +// Callback +client.transmissions.list(options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/transmissions/send_transmission_all_fields.js b/examples/transmissions/send_all_fields.js similarity index 95% rename from examples/transmissions/send_transmission_all_fields.js rename to examples/transmissions/send_all_fields.js index dea0cf7..4a7b2d2 100644 --- a/examples/transmissions/send_transmission_all_fields.js +++ b/examples/transmissions/send_all_fields.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , tranmission = { + , transmission = { options: { open_tracking: true, click_tracking: true @@ -50,7 +50,8 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(tranmission) +// Promise +client.transmissions.send(transmission) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -60,7 +61,7 @@ client.transmissions.send(tranmission) console.log(err); }); -// Using a callback +// Callback client.transmissions.send(tranmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/mime_parts.js b/examples/transmissions/send_mime_parts.js similarity index 97% rename from examples/transmissions/mime_parts.js rename to examples/transmissions/send_mime_parts.js index 2dcfe91..6888348 100644 --- a/examples/transmissions/mime_parts.js +++ b/examples/transmissions/send_mime_parts.js @@ -17,6 +17,7 @@ var key = 'YOURAPIKEY' } }; +// Promise client.transmissions.send(transmission) .then(data => { console.log('Congrats you can use our client library!'); @@ -27,7 +28,7 @@ client.transmissions.send(transmission) console.log(err); }); -// Using a callback +// Callback client.transmissions.send(transmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/rfc822.js b/examples/transmissions/send_rfc822.js similarity index 97% rename from examples/transmissions/rfc822.js rename to examples/transmissions/send_rfc822.js index bf0a6c7..02e90d1 100644 --- a/examples/transmissions/rfc822.js +++ b/examples/transmissions/send_rfc822.js @@ -10,6 +10,7 @@ var key = 'YOURAPIKEY' } }; +// Promise client.transmissions.send(transmission) .then(data => { console.log('Congrats you can use our client library!'); @@ -20,7 +21,7 @@ client.transmissions.send(transmission) console.log(err); }); -// Using a callback +// Callback client.transmissions.send(transmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/stored_recipients_inline_content.js b/examples/transmissions/send_stored_recipients_inline_content.js similarity index 97% rename from examples/transmissions/stored_recipients_inline_content.js rename to examples/transmissions/send_stored_recipients_inline_content.js index 080c312..c8bb4bb 100644 --- a/examples/transmissions/stored_recipients_inline_content.js +++ b/examples/transmissions/send_stored_recipients_inline_content.js @@ -15,6 +15,7 @@ var key = 'YOURAPIKEY' } }; +// Promise client.transmissions.send(transmission) .then(data => { console.log('Congrats you can use our client library!'); @@ -25,7 +26,7 @@ client.transmissions.send(transmission) console.log(err); }); -// Using a callback +// Callback client.transmissions.send(transmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/stored_recipients_stored_content.js b/examples/transmissions/send_stored_recipients_stored_content.js similarity index 90% rename from examples/transmissions/stored_recipients_stored_content.js rename to examples/transmissions/send_stored_recipients_stored_content.js index 3b4d7ba..6bf8790 100644 --- a/examples/transmissions/stored_recipients_stored_content.js +++ b/examples/transmissions/send_stored_recipients_stored_content.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , tranmission = { + , transmission = { recipients: { list_id: 'example-list' }, @@ -14,7 +14,8 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(tranmission) +// Promise +client.transmissions.send(transmission) .then(data => { console.log('Congrats you can use our client library!'); console.log(data); @@ -24,7 +25,7 @@ client.transmissions.send(tranmission) console.log(err); }); -// Using a callback +// Callback client.transmissions.send(tranmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/stored_template_send.js b/examples/transmissions/send_stored_template.js similarity index 79% rename from examples/transmissions/stored_template_send.js rename to examples/transmissions/send_stored_template.js index 99d1b3a..00a242b 100644 --- a/examples/transmissions/stored_template_send.js +++ b/examples/transmissions/send_stored_template.js @@ -8,11 +8,14 @@ var key = 'YOURAPIKEY' content: { template_id: 'ricks-template' }, - 'num_rcpt_errors': 3, recipients: [{ address: { email: 'rick.sanchez@rickandmorty100years.com', name: 'Rick Sanchez' } }] + } + , options = { + num_rcpt_errors: 3 }; -client.transmissions.send(transmission) +// Promise +client.transmissions.send(transmission, options) .then(data => { console.log('What up my glib globs! SparkPost!'); console.log(data); @@ -22,8 +25,8 @@ client.transmissions.send(transmission) console.log(err); }); -// Using a callback -client.transmissions.send(transmission, function(err, data) { +// Callback +client.transmissions.send(transmission, options, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/examples/transmissions/send_transmission_with_bcc.js b/examples/transmissions/send_with_bcc.js similarity index 98% rename from examples/transmissions/send_transmission_with_bcc.js rename to examples/transmissions/send_with_bcc.js index 9f24d76..e9d1804 100644 --- a/examples/transmissions/send_transmission_with_bcc.js +++ b/examples/transmissions/send_with_bcc.js @@ -35,6 +35,7 @@ var key = 'YOURAPIKEY' } }; +// Promise client.transmissions.send(transmission) .then(data => { console.log(data); @@ -45,7 +46,7 @@ client.transmissions.send(transmission) console.log(err); }); -// Using a callback +// Callback client.transmissions.send(transmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); diff --git a/examples/transmissions/send_transmission_with_cc.js b/examples/transmissions/send_with_cc.js similarity index 90% rename from examples/transmissions/send_transmission_with_cc.js rename to examples/transmissions/send_with_cc.js index f2b5286..f7a09d8 100644 --- a/examples/transmissions/send_transmission_with_cc.js +++ b/examples/transmissions/send_with_cc.js @@ -3,7 +3,7 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) - , tranmission = { + , transmission = { recipients: [ { address: { @@ -39,7 +39,8 @@ var key = 'YOURAPIKEY' } }; -client.transmissions.send(tranmission) +// Promise +client.transmissions.send(transmission) .then(data => { console.log('Congrats! You sent an email with cc using SparkPost!'); console.log(data); @@ -49,8 +50,8 @@ client.transmissions.send(tranmission) console.log(err); }); -// Using a callback -client.transmissions.send(tranmission, function(err, data) { +// Callback +client.transmissions.send(transmission, function(err, data) { if (err) { console.log('Whoops! Something went wrong'); console.log(err); diff --git a/lib/messageEvents.js b/lib/messageEvents.js index 86ce335..096cd67 100644 --- a/lib/messageEvents.js +++ b/lib/messageEvents.js @@ -1,6 +1,6 @@ 'use strict'; -var api = 'message-events'; +const api = 'message-events'; /* * "Class" declaration, Message Events API exposes one function: @@ -8,29 +8,26 @@ var api = 'message-events'; */ 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 - }; return client.get(options).asCallback(callback); } }; diff --git a/lib/transmissions.js b/lib/transmissions.js index 3c36974..0625780 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -1,8 +1,7 @@ 'use strict'; -let _ = require('lodash') - , Promise = require('./Promise'); const api = 'transmissions'; +const Promise = require('./Promise'); /* * "Class" declaration, Transmissions exposes three functions, one for sending a transmission, @@ -12,29 +11,17 @@ const api = 'transmissions'; module.exports = function(client) { return { - send: function(transmission, callback) { - var reqOpts; - - if (!transmission || typeof transmission === 'function') { - return Promise.reject(new Error('transmission object is required')).asCallback(callback); - } - - reqOpts = { - uri: api, - json: _.cloneDeep(transmission), - qs: {} - }; - - if (reqOpts.json.num_rcpt_errors) { - reqOpts.qs.num_rcpt_errors = reqOpts.json.num_rcpt_errors; - delete reqOpts.json.num_rcpt_errors; - } - - return client.post(reqOpts).asCallback(callback); - }, - all: function(options, callback) { + /** + * 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 = {}; @@ -47,7 +34,14 @@ module.exports = function(client) { return client.get(reqOpts).asCallback(callback); }, - find: function(id, callback) { + /** + * 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') { @@ -59,6 +53,35 @@ module.exports = function(client) { }; 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); + } + + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; + } + + reqOpts = { + uri: api, + json: transmission, + qs: options + }; + + return client.post(reqOpts).asCallback(callback); } }; diff --git a/test/spec/messageEvents.spec.js b/test/spec/messageEvents.spec.js index 45d8540..5b9fdfc 100644 --- a/test/spec/messageEvents.spec.js +++ b/test/spec/messageEvents.spec.js @@ -1,24 +1,28 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai') , Promise = require('../../lib/Promise'); -chai.use(sinonChai); +require('sinon-as-promised'); + +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Message Events Library', function() { - var client; + let client, messageEvents; beforeEach(function() { client = { - get: sinon.stub().returns(Promise.resolve({})) + 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', @@ -35,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'], @@ -57,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/transmissions.spec.js b/test/spec/transmissions.spec.js index 6fefa24..08fc0f0 100644 --- a/test/spec/transmissions.spec.js +++ b/test/spec/transmissions.spec.js @@ -23,14 +23,14 @@ describe('Transmissions Library', function() { describe('all Method', function() { it('should call client get method with the appropriate uri', function() { - return transmissions.all() + 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.all(function() { + transmissions.list(function() { expect(client.get.firstCall.args[0].uri).to.equal('transmissions'); done(); }); @@ -41,7 +41,7 @@ describe('Transmissions Library', function() { campaign_id: 'test-campaign' }; - return transmissions.all(options) + return transmissions.list(options) .then(function() { expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'}); }); @@ -52,7 +52,7 @@ describe('Transmissions Library', function() { template_id: 'test-template' }; - return transmissions.all(options) + return transmissions.list(options) .then(function() { expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'}); }); @@ -61,14 +61,14 @@ describe('Transmissions Library', function() { describe('find Method', function() { it('should call client get method with the appropriate uri', function() { - return transmissions.find('test') + return transmissions.get('test') .then(function() { expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'}); }); }); it('should throw an error if id is missing', function() { - return expect(transmissions.find()).to.be.rejectedWith('id is required'); + return expect(transmissions.get()).to.be.rejectedWith('id is required'); }); }); @@ -85,22 +85,34 @@ describe('Transmissions Library', function() { }); }); - it('should throw an error if options object is missing', function() { + 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() { - var options = { - campaign_id: 'test-campaign', - num_rcpt_errors: 3 - }; + var transmission = { + campaign_id: 'test-campaign' + } + , options = { + num_rcpt_errors: 3 + }; - return transmissions.send(options) + return transmissions.send(transmission, options) .then(function() { expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); }); }); + 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() { var options = { content: { From 39336530660b06e0e00617ced3ec163fd5d15b56 Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 2 Nov 2016 09:49:17 -0400 Subject: [PATCH 25/27] return body for sparkpost requests (#186) --- lib/sparkpost.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 1848fa1..30e1c1a 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -117,7 +117,7 @@ SparkPost.prototype.request = function(options, callback) { err = createSparkPostError(res, body); reject(err); } else { - response = body.results || body; + response = body; if (options.debug) { response.debug = res; } From 920a81f7bcad4b20c68e5ec6e38d82919b3b88fb Mon Sep 17 00:00:00 2001 From: Aydrian Date: Wed, 2 Nov 2016 14:41:09 -0400 Subject: [PATCH 26/27] Added setting debug in initialization (#188) * Added setting debug to initialization * Added note for debug about exposing api key * Added note about no support for older nodejs versions --- README.md | 23 +++++++++++++---------- docs/async.md | 8 ++------ lib/sparkpost.js | 7 ++++++- test/spec/sparkpost.spec.js | 20 ++++++++++++++++++-- 4 files changed, 39 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 8982770..d5ba8f2 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,8 @@ Before using this library, you must have: npm install sparkpost ``` +*Note: Node.js versions 0.10 and 0.12 are no longer supported. For versions < 4, please continue using [sparkpost v1.3.8](https://github.com/SparkPost/node-sparkpost/tree/1.3.8)* + ## Initialization **new SparkPost(apiKey[, options])** - Initialization @@ -40,24 +42,25 @@ npm install sparkpost * Required: no * Type: `Object` * set headers that apply to all requests +* `options.debug` + * Required: no + * Type: `Boolean` + * Default: `false` + * appends full response from request client as `debug` when `true` for debugging purposes
+ *Note: This will expose your api key to the client-side. Do not use in production.* ## Methods -* **request(options[, callback]) → `{Promise}`** + +*Note: All methods return promises and accept an optional last argument callback. [Read about how we handle callbacks and promises](/docs/async.md).* + +* **request(options[, callback])** * `options` - [see request modules options](https://github.com/mikeal/request#requestoptions-callback) * `options.uri` - can either be a full url or a path that is appended to `options.origin` used at initialization ([url.resolve](http://nodejs.org/api/url.html#url_url_resolve_from_to)) * `options.debug` - setting to `true` includes full response from request client for debugging purposes - * `callback` - executed after task is completed if provided* - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - results from API call - * `data.debug` - full response from request client when `options.debug` is `true` -* **get | post | put | delete(options[, callback]) → `{Promise}`** +* **get | post | put | delete(options[, callback])** * `options` - see request options - * `callback` - see request options * Request method will be overwritten and set to the same value as the name of these methods. -*callback is optional because all methods return a Promise. - ## Creating a SparkPost Client Passing in an API key diff --git a/docs/async.md b/docs/async.md index e300071..e998d08 100644 --- a/docs/async.md +++ b/docs/async.md @@ -11,9 +11,7 @@ let client = new SparkPost(key); client.templates.get(id) .then((data) => { - // this is either: - // a) the `results` key of the API response body, or - // b) the full API response body + // this the full API response body }) .catch((err) => { // handle the sad error @@ -33,8 +31,6 @@ client.templates.get(id, (err, data) => { return; } - // this is either: - // a) the `results` key of the API response body, or - // b) the full API response body + // this is the full API response body }); ``` diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 30e1c1a..67f1b2c 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -10,7 +10,8 @@ var version = require('../package.json').version //REST API Config Defaults defaults = { origin: 'https://api.sparkpost.com:443', - apiVersion: 'v1' + apiVersion: 'v1', + debug: false }; resolveUri = function(origin, uri) { @@ -66,6 +67,7 @@ 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); @@ -106,6 +108,9 @@ SparkPost.prototype.request = function(options, callback) { options.gzip = true; } + // 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}/ diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 7ada0d6..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; From 039c9f9f9291e3e4d0856095fa4aa9b2731cef71 Mon Sep 17 00:00:00 2001 From: "Aydrian J. Howard" Date: Fri, 4 Nov 2016 14:53:33 -0400 Subject: [PATCH 27/27] Updated sign up links --- CHANGELOG.md | 28 +++++++++++++++++++++++++++- README.md | 6 ++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c9d142d..d34a445 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,31 @@ This project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased][unreleased] +## [2.0.0] - 2016-11-04 - *breaking* +- [#188](https://github.com/SparkPost/node-sparkpost/pull/188) Added setting debug in initialization (@aydrian) +- [#186](https://github.com/SparkPost/node-sparkpost/pull/186) Return full body for sparkpost requests (@aydrian) +- [#184](https://github.com/SparkPost/node-sparkpost/pull/184) Standardized action verbs on remaining libraries (@aydrian) +- [#183](https://github.com/SparkPost/node-sparkpost/pull/183) Standardized action verbs for Webhooks (@aydrian) +- [#181](https://github.com/SparkPost/node-sparkpost/pull/181) Removed toApiFormat (@aydrian) +- [#177](https://github.com/SparkPost/node-sparkpost/pull/177) Refactored inbound domains library (@aydrian) +- [#173](https://github.com/SparkPost/node-sparkpost/pull/173) Updated tests and examples for transmissions (@aydrian) +- [#172](https://github.com/SparkPost/node-sparkpost/pull/172) Refactored subaccounts library (@aydrian) +- [#171](https://github.com/SparkPost/node-sparkpost/pull/171) Refactored relay webhooks library (@aydrian) +- [#170](https://github.com/SparkPost/node-sparkpost/pull/170) Refactored webhooks library (@aydrian) +- [#169](https://github.com/SparkPost/node-sparkpost/pull/169) Refactored templates library (@aydrian) +- [#168](https://github.com/SparkPost/node-sparkpost/pull/168) Refactored suppression list library (@aydrian) +- [#167](https://github.com/SparkPost/node-sparkpost/pull/167) Refactored sending domains library (@aydrian) +- [#166](https://github.com/SparkPost/node-sparkpost/pull/166) Refactored recipient lists library (@aydrian) +- [#163](https://github.com/SparkPost/node-sparkpost/pull/163) Set options.json=true for GET requests (@aydrian) +- [#162](https://github.com/SparkPost/node-sparkpost/pull/162) Removed SendGrid Compatibility (@aydrian) +- [#160](https://github.com/SparkPost/node-sparkpost/pull/160) Switch to using npm scripts instead of grunt (@aydrian) +- [#159](https://github.com/SparkPost/node-sparkpost/pull/159) Switched JSHint for ESLint with SparkPost config (@aydrian) +- [#158](https://github.com/SparkPost/node-sparkpost/pull/158) Refactored transmissions library (@aydrian) +- [#157](https://github.com/SparkPost/node-sparkpost/pull/157) Removed support for nodejs versions .10 & .12 (@aydrian) +- [#154](https://github.com/SparkPost/node-sparkpost/pull/154) Implement promise support (@aydrian) +- [#123](https://github.com/SparkPost/node-sparkpost/pull/123) Added json flag to base request and tests to check for JSON response (@aydrian) +- [#112](https://github.com/SparkPost/node-sparkpost/pull/112) Returns body.results or body as a response. Added debug support. (@aydrian) + ## [1.3.8] - 2016-08-26 - [#165](https://github.com/SparkPost/node-sparkpost/pull/165) Updated webhook update method to not send id in request (@aydrian) @@ -110,7 +135,8 @@ This project adheres to [Semantic Versioning](http://semver.org/). ## 0.1.0 - 2014-11-10 - First Release! -[unreleased]: https://github.com/sparkpost/node-sparkpost/compare/1.3.8...HEAD +[unreleased]: https://github.com/sparkpost/node-sparkpost/compare/2.0.0...HEAD +[2.0.0]: https://github.com/sparkpost/node-sparkpost/compare/1.3.8...2.0.0 [1.3.8]: https://github.com/sparkpost/node-sparkpost/compare/1.3.7...1.3.8 [1.3.7]: https://github.com/sparkpost/node-sparkpost/compare/1.3.6...1.3.7 [1.3.6]: https://github.com/sparkpost/node-sparkpost/compare/1.3.5...1.3.6 diff --git a/README.md b/README.md index d5ba8f2..09038d2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -[Sign up](https://app.sparkpost.com/sign-up?src=Dev-Website&sfdcid=70160000000pqBb) for a SparkPost account and visit our [Developer Hub](https://developers.sparkpost.com) for even more content. +[Sign up][sparkpost sign up] for a SparkPost account and visit our [Developer Hub](https://developers.sparkpost.com) for even more content. # Node.js Client Library @@ -12,7 +12,7 @@ The official Node.js binding for your favorite [SparkPost APIs](https://develope Before using this library, you must have: -* A shiny new SparkPost Account, [sign up for a new account](https://app.sparkpost.com/#/sign-up) or [login to SparkPost](https://app.sparkpost.com/) +* A shiny new SparkPost Account, [sign up for a new account][sparkpost sign up] or [login to SparkPost](https://app.sparkpost.com/) * A valid SparkPost API Key. Check out our [Support Center](https://support.sparkpost.com/) for information on how to [create API keys](https://support.sparkpost.com/customer/portal/articles/1933377-create-api-keys) ## Installation @@ -170,3 +170,5 @@ Once all the dependencies are installed, you can execute the unit tests using `n ### ChangeLog [See ChangeLog here](CHANGELOG.md) + +[sparkpost sign up]: https://app.sparkpost.com/sign-up?src=Dev-Website&sfdcid=701600000011daf