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/.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/.travis.yml b/.travis.yml index cf097c1..7b1424b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,10 @@ language: node_js node_js: -- '4.1' -- '4.0' -- '0.12' -- '0.10' -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/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/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 bdbe8b3..0000000 --- a/Gruntfile.js +++ /dev/null @@ -1,82 +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'), - jshint: { - files: [ - 'index.js', - 'lib/{,*/}*.js', - 'examples/{,*/}*.js' - ], - options: { - reporter: require('jshint-stylish'), - jshintrc: './.jshintrc' - } - }, - 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: { - 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', [ 'jshint' ]); - - // 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 ad86d29..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 @@ -21,8 +21,10 @@ 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 +**new SparkPost(apiKey[, options])** - Initialization * `apiKey` * Required: yes (unless key is stored in `SPARKPOST_API_KEY` environment variable) @@ -40,19 +42,23 @@ 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)** + +*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)) - * `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 -* **get | post | put | delete(options, callback)** + * `options.debug` - setting to `true` includes full response from request client for debugging purposes +* **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. ## Creating a SparkPost Client @@ -91,25 +97,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.body); -}); + }); ``` ## 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!', @@ -118,15 +126,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 @@ -147,20 +155,20 @@ 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) ### ChangeLog [See ChangeLog here](CHANGELOG.md) + +[sparkpost sign up]: https://app.sparkpost.com/sign-up?src=Dev-Website&sfdcid=701600000011daf 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/docs/async.md b/docs/async.md new file mode 100644 index 0000000..e998d08 --- /dev/null +++ b/docs/async.md @@ -0,0 +1,36 @@ +# 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 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 the full API response body +}); +``` diff --git a/docs/resources/inboundDomains.md b/docs/resources/inboundDomains.md index 81175c5..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.body); -}); - -``` - -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/docs/resources/messageEvents.md b/docs/resources/messageEvents.md index b0d0892..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.body); -}); - -``` - -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/recipientLists.md b/docs/resources/recipientLists.md index 5fa4ca6..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.body); -}); - -``` - -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/docs/resources/relayWebhooks.md b/docs/resources/relayWebhooks.md index 2d64a47..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.body); -}); - -``` - -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/docs/resources/sendingDomains.md b/docs/resources/sendingDomains.md index 0c11777..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.body); -}); - -``` - -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/docs/resources/subaccounts.md b/docs/resources/subaccounts.md index d948692..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.body); -}); -``` +Visit our examples section to see all of [our subaccount resource examples](/examples/subaccounts). diff --git a/docs/resources/suppressionList.md b/docs/resources/suppressionList.md index 388a543..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.body); -}); - -``` - -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/docs/resources/templates.md b/docs/resources/templates.md index fffab0d..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.body); -}); - -``` -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/docs/resources/transmissions.md b/docs/resources/transmissions.md index 3547ea7..4e0ed52 100644 --- a/docs/resources/transmissions.md +++ b/docs/resources/transmissions.md @@ -1,57 +1,25 @@ # 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. + +*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(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. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **find(transmissionID, callback)** +* **get(id[, callback])**
Retrieve the details about a transmission by its ID - * `transmissionID` - id of the transmission you want to look up **required** - * `callback` - see all function -* **send(options, callback)** + * `id` - id of the transmission you want to look up **required** +* **send(transmission[, options, callback])**
Sends a message by creating a new transmission - * `options.transmissionBody` - a transmission object **required** + * `transmission` - 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 - - -## Getting Started: Your First Mailing - -```javascript -var SparkPost = require('sparkpost') - , client = new SparkPost('YOUR API KEY'); -var reqObj = { - transmissionBody: { - 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' } }] - } -}; +## Examples -client.transmissions.send(reqObj, function(err, res) { - if (err) { - console.log('Whoops! Something went wrong'); - console.log(err); - } else { - console.log('Woohoo! You just sent your first mailing!'); - } -}); -``` -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/docs/resources/webhooks.md b/docs/resources/webhooks.md index 8a752ba..41d8dd6 100644 --- a/docs/resources/webhooks.md +++ b/docs/resources/webhooks.md @@ -1,65 +1,57 @@ # 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. + +*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 currently extant webhooks. - * `options.timezone` - `String` Standard timezone identification Default: `UTC` - * `callback` - executed after task is completed. **required** - * standard `callback(err, data)` - * `err` - any error that occurred - * `data` - full response from request client -* **describe(options, callback)** - 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 a new webhook - * `webhook` - a webhook object **required** - * `callback` - see all function -* **update(webhook, callback)** - Update an existing webhook - * `webhook` - a webhook object **required** - * `callback` - see all function -* **delete(id, callback)** - Delete an existing webhook - * `id` - the id of the webhook you want to delete **required** - * `callback` - see all function -* **validate(options, callback)** - 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)** - 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)** - 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)** - 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 +* **list([options])**
+ Lists all webhooks. + * `options.timezone` - the timezone to use for the `last_successful` and `last_failure` properties | Default: `UTC` + +* **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` + +* **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 => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); -## Examples +* **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** -```js -var SparkPost = require('sparkpost'); -var client = new SparkPost('YOUR_API_KEY'); +* **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** -client.webhooks.all(function(err, data) { - if(err) { - console.log(err); - return; - } +* **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. - console.log(data.body); -}); +* **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/baseObject/getDomainsList.js b/examples/baseObject/getDomainsList.js index f3c3ea8..452b106 100644 --- a/examples/baseObject/getDomainsList.js +++ b/examples/baseObject/getDomainsList.js @@ -7,11 +7,23 @@ var key = 'YOURAPIKEY' uri: 'metrics/domains' }; +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.body); }); 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 507f2a5..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 29c6936..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 76b4aaf..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 cc0f4ed..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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/examples/messageEvents/all_messageEvents.js b/examples/messageEvents/all_messageEvents.js deleted file mode 100644 index 5ad4ff3..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); - diff --git a/examples/messageEvents/search_campaignClicks.js b/examples/messageEvents/search_campaignClicks.js index 82b9e79..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' + }; -client.messageEvents.search(searchParams, function(err, res) { +// 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(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); - diff --git a/examples/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 c446367..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] + }; -client.messageEvents.search(searchParams, function(err, res) { +// 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(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); - diff --git a/examples/recipientLists/create_recipientList.js b/examples/recipientLists/create.js similarity index 50% rename from examples/recipientLists/create_recipientList.js rename to examples/recipientLists/create.js index 8f268f0..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, res) { +// 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(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/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 afabc46..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 6f24c7d..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/recipientLists/get_recipientList.js b/examples/recipientLists/get_recipientList.js deleted file mode 100644 index a4b1e82..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/recipientLists/get_recipientList_with_recipients.js b/examples/recipientLists/get_recipientList_with_recipients.js deleted file mode 100644 index 15d2415..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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.js b/examples/recipientLists/update.js new file mode 100644 index 0000000..3a881d4 --- /dev/null +++ b/examples/recipientLists/update.js @@ -0,0 +1,47 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , recipientList = { + id: 'EXISTING_TEST_ID' + , name: 'Test Recipient List' + , recipients: [ + { + address: { + email: 'test1@test.com' + } + }, + { + address: { + email: 'test2@test.com' + } + }, + { + address: { + email: 'test3@test.com' + } + } + ] + }; + +// 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('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/recipientLists/update_recipientList.js b/examples/recipientLists/update_recipientList.js deleted file mode 100644 index 9e4087e..0000000 --- a/examples/recipientLists/update_recipientList.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'EXISTING_TEST_ID' - , name: 'Test Recipient List' - , recipients: [ - { - address: { - email: 'test1@test.com' - } - } - , { - address: { - email: 'test2@test.com' - } - } - , { - address: { - email: 'test3@test.com' - } - } - ] - }; - -client.recipientLists.update(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/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 0475de2..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 e401783..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 272ca44..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 864f9e3..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 302e5eb..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our client library!'); - } -}); 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 ed7c207..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 ef4086e..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/sendingDomains/get_sendingDomain.js b/examples/sendingDomains/get_sendingDomain.js deleted file mode 100644 index 70e4df8..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 70% rename from examples/sendingDomains/update_sendingDomain.js rename to examples/sendingDomains/update.js index 9abe145..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, res) { +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(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/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 059722d..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/sendingDomains/verify_sendingDomain_dkim_only.js b/examples/sendingDomains/verify_sendingDomain_dkim_only.js deleted file mode 100644 index 35bfb7f..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/sendingDomains/verify_sendingDomain_spf_only.js b/examples/sendingDomains/verify_sendingDomain_spf_only.js deleted file mode 100644 index f640710..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/subaccounts/create.js b/examples/subaccounts/create.js new file mode 100644 index 0000000..1374705 --- /dev/null +++ b/examples/subaccounts/create.js @@ -0,0 +1,35 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , subaccount = { + name: 'Test Subaccount', + key_label: 'Test Subaccount key', + key_grants: [ + 'smtp/inject', + 'transmissions/modify' + ] + }; + +// Promise +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); + }); + +// Callback +client.subaccounts.create(subaccount, 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/create_subaccount.js b/examples/subaccounts/create_subaccount.js deleted file mode 100644 index ac6b37e..0000000 --- a/examples/subaccounts/create_subaccount.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - name: 'Test Subaccount' - , keyLabel: 'Test Subaccount key' - , keyGrants: [ - 'smtp/inject' - , 'transmissions/modify' - ] - }; - -client.subaccounts.create(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/subaccounts/get.js b/examples/subaccounts/get.js new file mode 100644 index 0000000..9f0e45a --- /dev/null +++ b/examples/subaccounts/get.js @@ -0,0 +1,27 @@ +'use strict'; + +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!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.subaccounts.get('123', 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/get_all_subaccounts.js b/examples/subaccounts/get_all_subaccounts.js deleted file mode 100644 index ea0cfa6..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/subaccounts/get_subaccount.js b/examples/subaccounts/get_subaccount.js deleted file mode 100644 index c207d8a..0000000 --- a/examples/subaccounts/get_subaccount.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.subaccounts.find(123, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/subaccounts/list.js b/examples/subaccounts/list.js new file mode 100644 index 0000000..877bdd1 --- /dev/null +++ b/examples/subaccounts/list.js @@ -0,0 +1,27 @@ +'use strict'; + +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!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// 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.js b/examples/subaccounts/update.js new file mode 100644 index 0000000..565a093 --- /dev/null +++ b/examples/subaccounts/update.js @@ -0,0 +1,31 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , subaccount = { + name: 'Test Subaccount', + status: 'suspended' + }; + +// Promise +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); + }); + +// Callback +client.subaccounts.update('123', subaccount, 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 deleted file mode 100644 index 02e16c3..0000000 --- a/examples/subaccounts/update_subaccount.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - subaccountId: 123 - , name: 'Test Subaccount' - , status: 'suspended' - }; - -client.subaccounts.update(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/suppressionList/checkStatus.js b/examples/suppressionList/checkStatus.js deleted file mode 100644 index c0a3e31..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 f315e9e..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - 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 fa1bbc3..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our client library!'); - } -}); diff --git a/examples/suppressionList/upsert.js b/examples/suppressionList/upsert.js index 2e14e11..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, res) { +// 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(res.body); 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 new file mode 100644 index 0000000..a459057 --- /dev/null +++ b/examples/suppressionList/upsert_bulk.js @@ -0,0 +1,47 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , listEntries = [ + { + recipient: 'test1@test.com', + transactional: false, + non_transactional: true, + description: 'Test description 1' + }, + { + recipient: 'test2@test.com', + transactional: true, + non_transactional: true, + description: 'Test description 2' + }, + { + recipient: 'test3@test.com', + transactional: true, + non_transactional: false, + description: 'Test description 3' + } + ]; + +// 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('Congrats you can use our client library!'); + console.log(data); + } +}); 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 a6f6ca4..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 a780bba..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 8f3f309..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 87a1c34..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/templates/get_template.js b/examples/templates/get_template.js deleted file mode 100644 index e4a41d4..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 261c314..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); 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 ca6a411..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/templates/update_template.js b/examples/templates/update_template.js deleted file mode 100644 index ebf570c..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, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/get.js b/examples/transmissions/get.js new file mode 100644 index 0000000..8aabe7c --- /dev/null +++ b/examples/transmissions/get.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.transmissions.get('YOUR-TRANSMISSION-KEY') + .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.transmissions.get('YOUR-TRANSMISSION-KEY', 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/transmissions/get_all_transmissions.js b/examples/transmissions/get_all_transmissions.js deleted file mode 100644 index cf56dbf..0000000 --- a/examples/transmissions/get_all_transmissions.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.transmissions.all(function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/get_transmission.js b/examples/transmissions/get_transmission.js deleted file mode 100644 index 2f75daa..0000000 --- a/examples/transmissions/get_transmission.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.transmissions.find('YOUR-TRANSMISSION-KEY', function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/get_transmissions_by_campaign.js b/examples/transmissions/get_transmissions_by_campaign.js deleted file mode 100644 index a1bc054..0000000 --- a/examples/transmissions/get_transmissions_by_campaign.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - campaign_id: 'my_campaign' - }; - -client.transmissions.all(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/get_transmissions_by_template.js b/examples/transmissions/get_transmissions_by_template.js deleted file mode 100644 index ed58259..0000000 --- a/examples/transmissions/get_transmissions_by_template.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - template_id: 'my_template' - }; - -client.transmissions.all(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/list.js b/examples/transmissions/list.js new file mode 100644 index 0000000..4ddeaeb --- /dev/null +++ b/examples/transmissions/list.js @@ -0,0 +1,25 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.transmissions.list() + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { + console.log(err); + }); + +// Callback +client.transmissions.list(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/transmissions/list_by_campaign.js b/examples/transmissions/list_by_campaign.js new file mode 100644 index 0000000..bd50150 --- /dev/null +++ b/examples/transmissions/list_by_campaign.js @@ -0,0 +1,29 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + campaign_id: 'my_campaign' + }; + +client.transmissions.list(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.transmissions.list(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/transmissions/list_by_template.js b/examples/transmissions/list_by_template.js new file mode 100644 index 0000000..28ff2ce --- /dev/null +++ b/examples/transmissions/list_by_template.js @@ -0,0 +1,30 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + template_id: 'my_template' + }; + +// Promise +client.transmissions.list(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.transmissions.list(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/transmissions/mime_parts.js b/examples/transmissions/mime_parts.js deleted file mode 100644 index dd949bf..0000000 --- a/examples/transmissions/mime_parts.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqObj = { - transmissionBody: { - recipients: [{ address: { email: 'john.doe@example.com' } }], - content: { - from: 'From Envelope ', - subject: 'Example Email for MIME Parts', - html: '

Hello World!

', - text: 'Hello World!' - }, - options: { - open_tracking: true, - click_tracking: true - } - } -}; - -client.transmissions.send(reqObj, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/rfc822.js b/examples/transmissions/rfc822.js deleted file mode 100644 index 56ce9e5..0000000 --- a/examples/transmissions/rfc822.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqObj = { - transmissionBody: { - 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(reqObj, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/send_all_fields.js b/examples/transmissions/send_all_fields.js new file mode 100644 index 0000000..4a7b2d2 --- /dev/null +++ b/examples/transmissions/send_all_fields.js @@ -0,0 +1,73 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + options: { + open_tracking: true, + click_tracking: true + }, + campaign_id: 'christmas_campaign', + metadata: { + user_type: 'students' + }, + substitution_data: { + sender: 'Big Store Team' + }, + recipients: [ + { + address: { + email: 'wilma@flintstone.com', + name: 'Wilma Flintstone' + }, + tags: [ + 'greeting', + 'prehistoric', + 'fred', + 'flintstone' + ], + metadata: { + place: 'Bedrock' + }, + substitution_data: { + customer_type: 'Platinum' + } + } + ], + content: { + from: { + name: 'Fred Flintstone', + email: 'fred@flintstone.com' + }, + subject: 'Big Christmas savings!', + reply_to: 'Christmas Sales ', + headers: { + 'X-Customer-Campaign-ID': 'christmas_campaign' + }, + text: 'Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}', + html: '

Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

Hurry, this offer is only to {{customer_type}}\n

{{sender}}

' + } + }; + +// Promise +client.transmissions.send(transmission) + .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.transmissions.send(tranmission, 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/transmissions/send_mime_parts.js b/examples/transmissions/send_mime_parts.js new file mode 100644 index 0000000..6888348 --- /dev/null +++ b/examples/transmissions/send_mime_parts.js @@ -0,0 +1,40 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + recipients: [{ address: { email: 'john.doe@example.com' } }], + content: { + from: 'From Envelope ', + subject: 'Example Email for MIME Parts', + html: '

Hello World!

', + text: 'Hello World!' + }, + options: { + open_tracking: true, + click_tracking: true + } + }; + +// Promise +client.transmissions.send(transmission) + .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.transmissions.send(transmission, 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/transmissions/send_rfc822.js b/examples/transmissions/send_rfc822.js new file mode 100644 index 0000000..02e90d1 --- /dev/null +++ b/examples/transmissions/send_rfc822.js @@ -0,0 +1,33 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + recipients: [{address: {email: 'john.doe@example.com'}}], + content: { + email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World' + } + }; + +// Promise +client.transmissions.send(transmission) + .then(data => { + console.log('Congrats you can use our client library!'); + onsole.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.transmissions.send(transmission, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/transmissions/send_stored_recipients_inline_content.js b/examples/transmissions/send_stored_recipients_inline_content.js new file mode 100644 index 0000000..c8bb4bb --- /dev/null +++ b/examples/transmissions/send_stored_recipients_inline_content.js @@ -0,0 +1,38 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + recipients: { + list_id: 'example-list' + }, + content: { + from: 'From Envelope ', + subject: 'Example Email for Stored List and Inline Content', + html: '

Hello World

', + text: 'Hello World!' + } + }; + +// Promise +client.transmissions.send(transmission) + .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.transmissions.send(transmission, 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/transmissions/send_stored_recipients_stored_content.js b/examples/transmissions/send_stored_recipients_stored_content.js new file mode 100644 index 0000000..6bf8790 --- /dev/null +++ b/examples/transmissions/send_stored_recipients_stored_content.js @@ -0,0 +1,37 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + recipients: { + list_id: 'example-list' + }, + content: { + from: 'From Envelope ', + subject: 'Example Email for Stored List and Template', + template_id: 'my-template' + } + }; + +// Promise +client.transmissions.send(transmission) + .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.transmissions.send(tranmission, 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/transmissions/send_stored_template.js b/examples/transmissions/send_stored_template.js new file mode 100644 index 0000000..00a242b --- /dev/null +++ b/examples/transmissions/send_stored_template.js @@ -0,0 +1,37 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + campaign_id: 'ricks-campaign', + content: { + template_id: 'ricks-template' + }, + recipients: [{ address: { email: 'rick.sanchez@rickandmorty100years.com', name: 'Rick Sanchez' } }] + } + , options = { + num_rcpt_errors: 3 + }; + +// Promise +client.transmissions.send(transmission, options) + .then(data => { + console.log('What up my glib globs! SparkPost!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.transmissions.send(transmission, options, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('What up my glib globs! SparkPost!'); + console.log(data); + } +}); diff --git a/examples/transmissions/send_transmission_all_fields.js b/examples/transmissions/send_transmission_all_fields.js deleted file mode 100644 index a41ccba..0000000 --- a/examples/transmissions/send_transmission_all_fields.js +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; - -var key = "YOURAPIKEY" - , SparkPost = require("sparkpost") - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { - options: { - open_tracking: true, - click_tracking: true - }, - campaign_id: "christmas_campaign", - return_path: "bounces-christmas-campaign@flintstone.com", - metadata: { - user_type: "students" - }, - substitution_data: { - sender: "Big Store Team" - }, - recipients: [ - { - return_path: "123@bounces.flintstone.com", - address: { - email: "wilma@flintstone.com", - name: "Wilma Flintstone" - }, - tags: [ - "greeting", - "prehistoric", - "fred", - "flintstone" - ], - metadata: { - place: "Bedrock" - }, - substitution_data: { - customer_type: "Platinum" - } - } - ], - content: { - from: { - name: "Fred Flintstone", - email: "fred@flintstone.com" - }, - subject: "Big Christmas savings!", - reply_to: "Christmas Sales ", - headers: { - "X-Customer-Campaign-ID": "christmas_campaign" - }, - text: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}", - html: "

Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

Hurry, this offer is only to {{customer_type}}\n

{{sender}}

" - } - } -}; - -client.transmissions.send(reqOpts, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log("Congrats you can use our SDK!"); - } -}); diff --git a/examples/transmissions/send_transmission_with_bcc.js b/examples/transmissions/send_transmission_with_bcc.js deleted file mode 100644 index 1b99388..0000000 --- a/examples/transmissions/send_transmission_with_bcc.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; - -var key = "YOURAPIKEY" - , SparkPost = require("sparkpost") - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { - recipients: [ - { - address: { - email: "original.recipient@example.com", - name: "Original Recipient" - }, - substitution_data: { - recipient_type: "Original" - } - }, - { - address: { - email: "bcc.recipient@example.com", - header_to: "'Original Recipient' " - }, - substitution_data: { - recipient_type: "BCC" - } - } - ], - content: { - from: { - name: "Node BCC Test", - email: "from@example.com" - }, - subject: "Example email using bcc", - text: "An example email using bcc with SparkPost to the {{recipient_type}} recipient.", - html: "

An example email using bcc with SparkPost to the {{recipient_type}} recipient.

" - } - } -}; - -client.transmissions.send(reqOpts, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log("Congrats! You sent an email with bcc using SparkPost!"); - } -}); diff --git a/examples/transmissions/send_transmission_with_cc.js b/examples/transmissions/send_transmission_with_cc.js deleted file mode 100644 index 3485b01..0000000 --- a/examples/transmissions/send_transmission_with_cc.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; - -var key = "YOURAPIKEY" - , SparkPost = require("sparkpost") - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { - recipients: [ - { - address: { - email: "original.recipient@example.com", - name: "Original Recipient" - }, - substitution_data: { - recipient_type: "Original" - } - }, - { - address: { - email: "cc.recipient@example.com", - name: "Carbon Copy Recipient", - header_to: "'Original Recipient' " - }, - substitution_data: { - recipient_type: "CC" - } - } - ], - content: { - from: { - name: "Node CC Test", - email: "from@example.com" - }, - headers: { - "CC": "'Carbon Copy Recipient' " - }, - subject: "Example email using cc", - text: "An example email using cc with SparkPost to the {{recipient_type}} recipient.", - html: "

An example email using cc with SparkPost to the {{recipient_type}} recipient.

" - } - } -}; - -client.transmissions.send(reqOpts, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log("Congrats! You sent an email with cc using SparkPost!"); - } -}); diff --git a/examples/transmissions/send_with_bcc.js b/examples/transmissions/send_with_bcc.js new file mode 100644 index 0000000..e9d1804 --- /dev/null +++ b/examples/transmissions/send_with_bcc.js @@ -0,0 +1,58 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + recipients: [ + { + address: { + email: 'original.recipient@example.com', + name: 'Original Recipient' + }, + substitution_data: { + recipient_type: 'Original' + } + }, + { + address: { + email: 'bcc.recipient@example.com', + header_to: '"Original Recipient" ' + }, + substitution_data: { + recipient_type: 'BCC' + } + } + ], + content: { + from: { + name: 'Node BCC Test', + email: 'from@example.com' + }, + subject: 'Example email using bcc', + text: 'An example email using bcc with SparkPost to the {{recipient_type}} recipient.', + html: '

An example email using bcc with SparkPost to the {{recipient_type}} recipient.

' + } + }; + +// Promise +client.transmissions.send(transmission) + .then(data => { + console.log(data); + console.log('Congrats! You sent an email with bcc using SparkPost!'); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.transmissions.send(transmission, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats! You sent an email with bcc using SparkPost!'); + console.log(data); + } +}); diff --git a/examples/transmissions/send_with_cc.js b/examples/transmissions/send_with_cc.js new file mode 100644 index 0000000..f7a09d8 --- /dev/null +++ b/examples/transmissions/send_with_cc.js @@ -0,0 +1,62 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , transmission = { + recipients: [ + { + address: { + email: 'original.recipient@example.com', + name: 'Original Recipient' + }, + substitution_data: { + recipient_type: 'Original' + } + }, + { + address: { + email: 'cc.recipient@example.com', + name: 'Carbon Copy Recipient', + header_to: '"Original Recipient" ' + }, + substitution_data: { + recipient_type: 'CC' + } + } + ], + content: { + from: { + name: 'Node CC Test', + email: 'from@example.com' + }, + headers: { + 'CC': '"Carbon Copy Recipient" ' + }, + subject: 'Example email using cc', + text: 'An example email using cc with SparkPost to the {{recipient_type}} recipient.', + html: '

An example email using cc with SparkPost to the {{recipient_type}} recipient.

' + } + }; + +// Promise +client.transmissions.send(transmission) + .then(data => { + console.log('Congrats! You sent an email with cc using SparkPost!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.transmissions.send(transmission, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats! You sent an email with cc using SparkPost!'); + console.log(data); + } +}); diff --git a/examples/transmissions/stored_recipients_inline_content.js b/examples/transmissions/stored_recipients_inline_content.js deleted file mode 100644 index a087db5..0000000 --- a/examples/transmissions/stored_recipients_inline_content.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqObj = { - transmissionBody: { - recipients: { - list_id: 'example-list' - }, - content: { - from: 'From Envelope ', - subject: 'Example Email for Stored List and Inline Content', - html: '

Hello World

', - text: 'Hello World!' - } - } -}; - -client.transmissions.send(reqObj, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/stored_recipients_stored_content.js b/examples/transmissions/stored_recipients_stored_content.js deleted file mode 100644 index 2609013..0000000 --- a/examples/transmissions/stored_recipients_stored_content.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { - recipients: { - list_id: 'example-list' - }, - content: { - from: 'From Envelope ', - subject: 'Example Email for Stored List and Template', - template_id: 'my-template' - } - } -}; - -client.transmissions.send(reqOpts, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/transmissions/stored_template_send.js b/examples/transmissions/stored_template_send.js deleted file mode 100644 index 5189262..0000000 --- a/examples/transmissions/stored_template_send.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -var reqOpts = { - transmissionBody: { - campaignId: 'ricks-campaign', - content: { - template_id: 'ricks-template' - }, - 'num_rcpt_errors': 3, - recipients: [{ address: { email: 'rick.sanchez@rickandmorty100years.com', name: 'Rick Sanchez' } }] - } -}; - -client.transmissions.send(reqOpts, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('What up my glib globs! SparkPost!'); - } -}); diff --git a/examples/webhooks/create.js b/examples/webhooks/create.js new file mode 100644 index 0000000..97b532c --- /dev/null +++ b/examples/webhooks/create.js @@ -0,0 +1,38 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , webhook = { + name: 'Test Webhook', + target: 'http://client.test.com/test-webhook', + auth_token: 'AUTH_TOKEN', + events: [ + 'delivery', + 'injection', + 'open', + 'click' + ] + }; + +// Promise +client.webhooks.create(webhook) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.create(webhook, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/webhooks/create_webhook.js b/examples/webhooks/create_webhook.js deleted file mode 100644 index 1d1b19d..0000000 --- a/examples/webhooks/create_webhook.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , webhook = { - name: 'Test webhook' - , target: 'http://client.test.com/test-webhook' - , auth_token: 'AUTH_TOKEN' - , events: [ - 'delivery', - 'injection', - 'open', - 'click' - ] - }; - -client.webhooks.create(webhook, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/webhooks/delete.js b/examples/webhooks/delete.js new file mode 100644 index 0000000..725e342 --- /dev/null +++ b/examples/webhooks/delete.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.webhooks.delete('TEST_WEBHOOK_UUID') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.delete('TEST_WEBHOOK_UUID', function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/webhooks/delete_webhook.js b/examples/webhooks/delete_webhook.js deleted file mode 100644 index 95f75cf..0000000 --- a/examples/webhooks/delete_webhook.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.webhooks['delete']('TEST_WEBHOOK_UUID', function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/webhooks/describe_webhook.js b/examples/webhooks/describe_webhook.js deleted file mode 100644 index 99e9020..0000000 --- a/examples/webhooks/describe_webhook.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'TEST_WEBHOOK_UUID' - , timezone: 'America/New_York' - }; - -client.webhooks.describe(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/webhooks/get.js b/examples/webhooks/get.js new file mode 100644 index 0000000..57cdbb6 --- /dev/null +++ b/examples/webhooks/get.js @@ -0,0 +1,30 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + timezone: 'America/New_York' + }; + +// Promise +client.webhooks.get('TEST_WEBHOOK_UUID', options) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.get('TEST_WEBHOOK_UUID', options, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/webhooks/getBatchStatus.js b/examples/webhooks/getBatchStatus.js index d527cc3..2826764 100644 --- a/examples/webhooks/getBatchStatus.js +++ b/examples/webhooks/getBatchStatus.js @@ -4,15 +4,27 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { - id: 'TEST_WEBHOOK_UUID' - , limit: 1000 + limit: 1000 }; -client.webhooks.getBatchStatus(options, function(err, res) { +// Promise +client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', options) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/webhooks/getDocumentation.js b/examples/webhooks/getDocumentation.js index d9acc9f..8319814 100644 --- a/examples/webhooks/getDocumentation.js +++ b/examples/webhooks/getDocumentation.js @@ -4,11 +4,24 @@ var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key); -client.webhooks.getDocumentation(function(err, res) { +// Promise +client.webhooks.getDocumentation() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.getDocumentation(function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/webhooks/getSamples.js b/examples/webhooks/getSamples.js index 6930d77..3843865 100644 --- a/examples/webhooks/getSamples.js +++ b/examples/webhooks/getSamples.js @@ -7,11 +7,24 @@ var key = 'YOURAPIKEY' events: 'bounce' }; -client.webhooks.getSamples(options, function(err, res) { +// Promise +client.webhooks.getSamples(options) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.getSamples(options, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); + console.log('Congrats you can use our client library!'); + console.log(data); } }); diff --git a/examples/webhooks/get_all_webhooks.js b/examples/webhooks/get_all_webhooks.js deleted file mode 100644 index 3f36053..0000000 --- a/examples/webhooks/get_all_webhooks.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key); - -client.webhooks.all(function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/webhooks/list.js b/examples/webhooks/list.js new file mode 100644 index 0000000..10f4756 --- /dev/null +++ b/examples/webhooks/list.js @@ -0,0 +1,27 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key); + +// Promise +client.webhooks.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.list(function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/webhooks/update.js b/examples/webhooks/update.js new file mode 100644 index 0000000..8c33443 --- /dev/null +++ b/examples/webhooks/update.js @@ -0,0 +1,34 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , webhook = { + name: 'Renamed Test Webhook', + events: [ + 'policy_rejection', + 'delay' + ] + }; + +// Promise +client.webhooks.update('TEST_WEBHOOK_UUID', webhook) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.update('TEST_WEBHOOK_UUID', webhook, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/webhooks/update_webhook.js b/examples/webhooks/update_webhook.js deleted file mode 100644 index 05284c5..0000000 --- a/examples/webhooks/update_webhook.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , webhook = { - id: 'TEST_WEBHOOK_UUID' - , name: 'Renamed Test webhook' - , events: [ - 'policy_rejection', - 'delay' - ] - }; - -client.webhooks.update(webhook, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/examples/webhooks/validate.js b/examples/webhooks/validate.js new file mode 100644 index 0000000..d1a312f --- /dev/null +++ b/examples/webhooks/validate.js @@ -0,0 +1,32 @@ +'use strict'; + +var key = 'YOURAPIKEY' + , SparkPost = require('sparkpost') + , client = new SparkPost(key) + , options = { + message: { + msys: {} + } + }; + +// Promise +client.webhooks.validate('TEST_WEBHOOK_UUID', options) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.validate('TEST_WEBHOOK_UUID', options, function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); diff --git a/examples/webhooks/validate_webhook.js b/examples/webhooks/validate_webhook.js deleted file mode 100644 index 5b885ba..0000000 --- a/examples/webhooks/validate_webhook.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var key = 'YOURAPIKEY' - , SparkPost = require('sparkpost') - , client = new SparkPost(key) - , options = { - id: 'TEST_WEBHOOK_UUID' - , message: { - msys: {} - } - }; - -client.webhooks.validate(options, function(err, res) { - if (err) { - console.log(err); - } else { - console.log(res.body); - console.log('Congrats you can use our SDK!'); - } -}); diff --git a/lib/Promise.js b/lib/Promise.js new file mode 100644 index 0000000..7bf5c2c --- /dev/null +++ b/lib/Promise.js @@ -0,0 +1,31 @@ +'use strict'; + +/** + * asCallback method mimics bluebird and allows + * promise object to handle an optional nodeback + * + * @param cb {Function} + * @return Promise + * + * @example + * function eitherOr(options, callback) { + * return promiseThingy(options).asCallback(callback); + * } + */ +Promise.prototype.asCallback = function(cb) { + if (typeof cb !== 'function') { + cb = noop; + } + + return this.then((result) => { + cb(null, result); + return this; + }).catch((err) => { + cb(err); + return this; + }); +}; + +function noop() {} + +module.exports = Promise; diff --git a/lib/SendGridCompatibility/Email.js b/lib/SendGridCompatibility/Email.js deleted file mode 100644 index a523122..0000000 --- a/lib/SendGridCompatibility/Email.js +++ /dev/null @@ -1,102 +0,0 @@ -'use strict'; - -/** - * Email object constructor - * - * @param options object that contains initial values - */ -function Email(options){ - for (var option in options) { - this[option] = options[option]; - } -} - -/** - * SendGrid email compatibility functions - * - * @param Most have a single value to map - * Add functions will often contain a key / value pair - */ -Email.prototype.addTo = function (address){ - if (this.to === undefined){ - this.to = address; - } else if (typeof this.to === 'string'){ - this.to = [this.to]; - this.to.push(address); - } else { - this.to.push(address); - } -}; -Email.prototype.setFrom = function (address){ - this.from = address; -}; -Email.prototype.setSubject = function (subject){ - this.subject = subject; -}; -Email.prototype.setText = function (text){ - this.text = text; -}; -Email.prototype.setHtml = function (html){ - this.html = html; -}; -Email.prototype.addHeader = function (key, value){ - if (this.headers === undefined){ - this.headers = {}; - } - this.headers[key] = value; -}; -Email.prototype.setHeaders = function (headers){ - this.headers = headers; -}; -Email.prototype.addSubstitution = function (key, value){ - if (this.sub === undefined){ - this.sub = {}; - } - if (typeof value === 'string'){ - this.sub[key] = [value]; - } else { - this.sub[key] = value; - } -}; -Email.prototype.setSubstitutions = function (substitutions){ - this.sub = substitutions; -}; -Email.prototype.addSection = function (key, value){ - if (this.section === undefined){ - this.section = {}; - } - this.section[key] = value; -}; -Email.prototype.setSections = function (sections){ - this.section = sections; -}; -// SparkPost doesn't currently support addUniqueArg, throw an error -Email.prototype.addUniqueArg = function (){ - throw new Error('Unique Argument compatibility is not supported.'); -}; -// SparkPost doesn't currently support setUniqueArgs, throw an error -Email.prototype.setUniqueArgs = function (){ - throw new Error('Unique Argument compatibility is not supported.'); -}; -// SparkPost doesn't currently support addCategory, throw an error -Email.prototype.addCategory = function (){ - throw new Error('Category compatibility is not supported.'); -}; -// SparkPost doesn't currently support setCategories, throw an error -Email.prototype.setCategories = function (){ - throw new Error('Category compatibility is not supported.'); -}; -// SparkPost doesn't currently support addFilter, throw an error -Email.prototype.addFilter = function (){ - throw new Error('Filter compatibility is not supported.'); -}; -// SparkPost doesn't currently support setFilters, throw an error -Email.prototype.setFilters = function (){ - throw new Error('Filter compatibility is not supported.'); -}; -// SparkPost doesn't currently support addFile, throw an error -Email.prototype.addFile = function (){ - throw new Error('File compatibility is not supported.'); -}; - -module.exports = Email; diff --git a/lib/SendGridCompatibility/index.js b/lib/SendGridCompatibility/index.js deleted file mode 100644 index b5d605e..0000000 --- a/lib/SendGridCompatibility/index.js +++ /dev/null @@ -1,127 +0,0 @@ -'use strict'; -var _ = require('lodash'); -var url = require('url'); -var SparkPost = require('../sparkpost'); - -/** - * SendGrid compatibility constructor - * Responsible for taking the api key and config options and - * translating them into a format compatible with SparkPost's - * options. - * - * @param username: dropped SendGrid username string - * @param apiKey: api key string - * @param options: optional additional options object - */ -var sendgrid = function(username, apiKey, options) { - options = options || {}; - var urlOpts = { - protocol: options.protocol - , hostname: options.host - , port: options.port - } - , opts = { - endpoint: url.format(urlOpts) - }; - - this.client = new SparkPost(apiKey, opts); -}; - -/** - * Private Method for translating a user's SendGrid substitutions and sections - * to a consolidated SparkPost substitutionData object - * - * @param payload: SendGrid formatted object or SendGrid Email object to - * be translated into a SparkPost payload - * @returns object: substitutionData object as per SparkPost payload format - */ -var consolidateSubstitutionData = function(payload) { - var substitutionData = {}; - if (payload.sub !== undefined && payload.section !== undefined){ - substitutionData = _.merge(payload.sub, payload.section); - } else if (payload.sub !== undefined){ - substitutionData = payload.sub; - } else if (payload.section !== undefined){ - substitutionData = payload.section; - } - return substitutionData; -}; - -/** - * Private Method for translating a user's SendGrid to and toname to a recipients - * array that the transmissions "Class" can understand - * - * @param payload: SendGrid formatted object or SendGrid Email object to - * be translated into a SparkPost payload - * @returns array: recipients array as per SparkPost payload format - */ -var parseTo = function(payload){ - var recipients = []; - if (typeof payload.to === 'string'){ - payload.to = [payload.to]; - } - for (var i = 0; payload.to.length > i; i++){ - var to = { - address: { - email: payload.to[i] - } - }; - if (payload.toname !== undefined && payload.toname[i] !== undefined){ - to.address.name = payload.toname[i]; - } - recipients.push(to); - } - return recipients; -}; - -/** - * Private Method for translating a user's SendGrid payload to a format - * that the transmissions "Class" can understand - * - * @param payload: SendGrid formatted object or SendGrid Email object to - * be translated into a SparkPost payload - * @returns object: translation from SendGrid payload to SparkPost payload - */ -var translatePayload = function(payload) { - var sub = consolidateSubstitutionData(payload) - , input = { - recipients: [], - from: '', - html: '', - text: '', - subject: '' - }; - - if (payload.to !== undefined){ - input.recipients = parseTo(payload); - } - input.from = payload.from; - if (payload.fromname !== undefined){ - input.from = input.from + ' <' + payload.fromname + '>'; - } - input.subject = payload.subject; - input.text = payload.text; - input.html = payload.html; - input.replyTo = payload.replyto; - input.customHeaders = payload.headers; - input.substitutionData = (Object.keys(sub).length > 0) ? sub : undefined; - - return input; -}; - -/** - * An exposed function of SendGridCompatibility that calls upon - * private helper methods to translate an Email or inline object - * and then pass that content to the transmissions send function. - * - * @param payload: SendGrid formatted object or SendGrid Email object to - * be translated into a SparkPost payload and sent - */ -sendgrid.prototype.send = function(payload, callback) { - var translated = translatePayload(payload); - this.client.transmissions.send({transmissionBody: translated }, callback); -}; - -sendgrid.prototype.Email = require('./Email'); - -module.exports = sendgrid; diff --git a/lib/inboundDomains.js b/lib/inboundDomains.js index 56e27c3..a44485b 100644 --- a/lib/inboundDomains.js +++ b/lib/inboundDomains.js @@ -1,67 +1,79 @@ 'use strict'; -var api = 'inbound-domains'; +const api = 'inbound-domains'; +const Promise = require('./Promise'); module.exports = function(client) { - var inboundDomains = { - all: function(callback) { + return { + /** + * List an overview of all inbound domains in the account. + * + * @param {RequestCb} [callback] + * @returns {Promise} + */ + list: function(callback) { var options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - find: function(domain, callback) { - if(typeof domain === 'function') { - callback = domain; - domain = null; - } + /** + * Get an inbound domain by its domain name + * + * @param {string} domain + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(domain, callback) { + let options; - if(!domain) { - callback(new Error('domain is required')); - return; + if (!domain || typeof domain !== 'string') { + return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - create: function(domain, callback) { - if(typeof domain === 'function') { - callback = domain; - domain = null; - } + /** + * Create a new inbound domain + * + * @param {Object} createOpts + * @param {RequestCb} [callback] + * @returns {Promise} + */ + create: function(createOpts, callback) { + let options; - if(!domain) { - callback(new Error('domain is required')); - return; + if (!createOpts || typeof createOpts !== 'object') { + return Promise.reject(new Error('create options are required')).asCallback(callback); } - var options = { + options = { uri: api - , json: { - domain: domain - } + , json: createOpts }; - client.post(options, callback); + return client.post(options, callback).asCallback(callback); }, + /** + * Delete an existing inbound domain + * + * @param {string} domain + * @param {RequestCb} [callback] + * @returns {Promise} + */ delete: function(domain, callback) { - if (typeof domain === 'function') { - callback = domain; - domain = null; - } + let options; - if (!domain) { - callback(new Error('domain is required')); - return; + if (!domain || typeof domain !== 'string') { + return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; - client.delete(options, callback); + return client.delete(options).asCallback(callback); } }; - - return inboundDomains; }; diff --git a/lib/messageEvents.js b/lib/messageEvents.js index e46f763..096cd67 100644 --- a/lib/messageEvents.js +++ b/lib/messageEvents.js @@ -1,37 +1,34 @@ 'use strict'; -var api = 'message-events'; +const api = 'message-events'; /* * "Class" declaration, Message Events API exposes one function: * - search: retrieves list of message events according to given params */ -module.exports = function (client) { +module.exports = function(client) { return { + /** + * Search for message events using given parameters + * + * @param {Object} parameters + * @param {RequestCb} [callback] + * @returns {Promise} + */ search: function(parameters, callback) { - var arrayParams = [ - 'bounce_classes', - 'campaign_ids', - 'events', - 'friendly_froms', - 'message_ids', - 'recipients', - 'template_ids', - 'transmission_ids' - ] - , options; + var options = { + uri: api + , qs: {} + }; - arrayParams.forEach(function(paramname) { + Object.keys(parameters).forEach(function(paramname) { if (Array.isArray(parameters[paramname])) { - parameters[paramname] = parameters[paramname].toString(); + options.qs[paramname] = parameters[paramname].join(','); + } else { + options.qs[paramname] = parameters[paramname]; } }); - - options = { - uri: api - , qs: parameters - }; - client.get(options, callback); + return client.get(options).asCallback(callback); } }; }; diff --git a/lib/recipientLists.js b/lib/recipientLists.js index cfa80e4..1644038 100644 --- a/lib/recipientLists.js +++ b/lib/recipientLists.js @@ -1,97 +1,138 @@ 'use strict'; -var api = 'recipient-lists' - , toApiFormat = require('./toApiFormat'); +const Promise = require('./Promise'); +const api = 'recipient-lists'; module.exports = function(client) { - var recipientLists = { - all: function(callback) { + return { + /** + * Get a list of all your recipient lists + * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-retrieve-get + * + * @param {RequestCb} [callback] + * @return {Promise} + */ + list: function(callback) { var reqOpts = { uri: api }; - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - find: function(options, callback) { + + /** + * Get a list of all your recipient lists + * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-list-get + * + * @param {string} id - Unique ID of the list to return + * @param {Object} options - Hash of request options + * @param {RequestCb} [callback] + * @return {Promise} + */ + get: function(id, options, callback) { + var reqOpts; options = options || {}; - if(!options.id) { - callback(new Error('id is required')); - return; + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; } - var reqOpts = { - uri: api + '/' + options.id - }; - - if(options.show_recipients) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.show_recipients = options.show_recipients; + if (!id) { + return Promise.reject(new Error('id is required')).asCallback(callback); } - client.get(reqOpts, callback); - }, - create: function(options, callback) { - options = options || {}; + reqOpts = { + uri: api + '/' + id, + qs: options + }; - if(!options.recipients) { - callback(new Error('recipients list is required')); - return; - } + return client.get(reqOpts).asCallback(callback); + }, - var reqOpts = { - uri: api - }; - if (options.num_rcpt_errors) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors; - delete options.num_rcpt_errors; + /** + * Create a new recipient list + * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-create-post + * + * @param {Object} recipientList - recipient list object + * @param {Array} recipientList.recipients - Array of recipient objects + * @param {RequestCb} callback + * @return {Promise} + */ + create: function(recipientList, callback) { + var reqOpts; + + if (!recipientList || typeof recipientList !== 'object' || !recipientList.recipients) { + return Promise.reject(new Error('recipient list is required')).asCallback(callback); } - reqOpts.json = toApiFormat(options); + reqOpts = { + uri: api, + json: recipientList, + qs: { + num_rcpt_errors: recipientList.num_rcpt_errors + } + }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - options = options || {}; - if(!options.id) { - callback(new Error('recipients list id is required')); - return; + /** + * Update an existing list + * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-update-put + * + * @param {string} id - Unique ID of the list to be updated + * @param {Object} recipientList - recipient list object + * @param {Array} recipientList.recipients - Array of recipient objects + * @param {RequestCb} callback + * @return {Promise} + * + */ + update: function(id, recipientList, callback) { + var reqOpts; + + if (!id) { + return Promise.reject(new Error('recipient list id is required')).asCallback(callback); } - var reqOpts = { - uri: api + '/' + options.id - }; - - if (options.num_rcpt_errors) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors; - delete options.num_rcpt_errors; + if (!recipientList || typeof recipientList === 'function') { + return Promise.reject(new Error('recipient list is required')).asCallback(callback); } - reqOpts.json = toApiFormat(options); + reqOpts = { + uri: api + '/' + id, + json: recipientList, + qs: { + num_rcpt_errors: recipientList.num_rcpt_errors + } + }; - client.put(reqOpts, callback); - } - }; + return client.put(reqOpts).asCallback(callback); + }, - recipientLists['delete'] = function(id, callback) { - if (typeof id === 'function') { - callback = id; - id = null; - } + /** + * Delete an existing recipient list + * https://developers.sparkpost.com/api/recipient-lists#recipient-lists-delete-delete + * + * @param {string} id - ID of the list to be updated + * @param {RequestCb} callback + * @return {Promise} + * + */ + delete: function(id, callback) { + var reqOpts; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); + } - if (!id) { - callback(new Error('id is required')); - return; - } + reqOpts = { + uri: api + '/' + id + }; - var reqOpts = { - uri: api + '/' + id - }; - client['delete'](reqOpts, callback); + return client.delete(reqOpts).asCallback(callback); + } }; - return recipientLists; }; diff --git a/lib/relayWebhooks.js b/lib/relayWebhooks.js index dc22bce..033fef9 100644 --- a/lib/relayWebhooks.js +++ b/lib/relayWebhooks.js @@ -1,114 +1,106 @@ 'use strict'; -var api = 'relay-webhooks'; - -var toApiFormat = function(input) { - var model = { - match: {} - }; - - model.target = input.target; - model.match.domain = input.domain; - - model.name = input.name; - model.auth_token = input.authToken; - model.match.protocol = input.protocol; - - return model; -}; +const Promise = require('./Promise'); +const api = 'relay-webhooks'; module.exports = function(client) { - var relayWebhooks = { - all: function(callback) { - var reqOpts = { + return { + /** + * List all relay webhooks + * + * @param {RequestCb} [callback] + * @returns {Promise} + */ + list: function(callback) { + let reqOpts = { uri: api }; - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - find: function(relayWebhookId, callback) { - if(typeof relayWebhookId === 'function') { - callback = relayWebhookId; - relayWebhookId = null; - } - - if(!relayWebhookId) { - callback(new Error('relayWebhookId is required')); - return; + /** + * Get details about a specified relay webhook by its id + * + * @param {string} id - the id of the relay webhook you want to look up + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(id, callback) { + let options; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - var options = { - uri: api + '/' + relayWebhookId + options = { + uri: api + '/' + id }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - create: function(options, callback) { - if(typeof options === 'function') { - callback = options; - options = null; - } - - if(!options) { - callback(new Error('options are required')); - return; + /** + * Create a new relay webhook + * + * @param {Object} webhook - an object of [relay webhook attributes]{https://developers.sparkpost.com/api/relay-webhooks#header-relay-webhooks-object-properties} + * @param {RequestCb} [callback] + * @returns {Promise} + */ + create: function(webhook, callback) { + let reqOpts; + + if (!webhook || typeof webhook !== 'object') { + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - if(!options.target) { - callback(new Error('target is required in options')); - return; - } - - if(!options.domain) { - callback(new Error('domain is required in options')); - return; - } - - var reqOpts = { + reqOpts = { uri: api - , json: toApiFormat(options) + , json: webhook }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - if(typeof options === 'function') { - callback = options; - options = null; - } - - if(!options) { - callback(new Error('options are required')); - return; + /** + * Update an existing relay webhook + * + * @param {string} id - the id of the relay webhook you want to update + * @param {Object} webhook - an object of [relay webhook attributes]{https://developers.sparkpost.com/api/relay-webhooks#header-relay-webhooks-object-properties} + * @param {RequestCb} [callback] + * @returns {Promise} + */ + update: function(id, webhook, callback) { + let reqOpts; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!options.relayWebhookId) { - callback(new Error('relayWebhookId is required in options')); - return; + if (!webhook || typeof webhook !== 'object') { + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - var relayWebhookId = options.relayWebhookId; - var reqOpts = { - uri: api + '/' + relayWebhookId - , json: toApiFormat(options) + reqOpts = { + uri: api + '/' + id + , json: webhook }; - client.put(reqOpts, callback); - }, - delete: function(relayWebhookId, callback) { - if (typeof relayWebhookId === 'function') { - callback = relayWebhookId; - relayWebhookId = null; - } - if (!relayWebhookId) { - callback(new Error('relayWebhookId is required')); - return; + return client.put(reqOpts).asCallback(callback); + }, + /** + * Delete an existing relay webhook + * + * @param {string} id - the id of the relay webhook you want to delete + * @param {RequestCb} [callback] + * @returns {Promise} + */ + delete: function(id, callback) { + let options; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - var options = { - uri: api + '/' + relayWebhookId + options = { + uri: api + '/' + id }; - client.delete(options, callback); + return client.delete(options, callback).asCallback(callback); } }; - - return relayWebhooks; }; diff --git a/lib/sendingDomains.js b/lib/sendingDomains.js index b85e357..faf3c70 100644 --- a/lib/sendingDomains.js +++ b/lib/sendingDomains.js @@ -1,122 +1,142 @@ 'use strict'; -var api = 'sending-domains' - , toApiFormat = require('./toApiFormat'); - -/* - * "Class" declaration, Sending Domains API exposes five functions: - * - create: creates a new sending domain - * - update: updates an existing sending domain - * - delete: deletes an existing sending domain - * - verify: validates specified verification field types on a sending domain - * - all: retreives a list of sending domains - * - find: retreives info about a specific sending domain - */ -module.exports = function (client) { - - var sendingDomains = { - all: function (callback) { //list - var options = { +const Promise = require('./Promise'); +const api = 'sending-domains'; + +module.exports = function(client) { + + return { + /** + * Lists all sending domains + * + * @param {RequestCb} [callback] + * @return {Promise} + */ + list: function(callback) { + let options = { uri: api }; - client.get(options, callback); + + return client.get(options).asCallback(callback); }, - find: function (domain, callback) { //retrieve - if(typeof domain === 'function') { - callback = domain; - domain = null; - } - if(!domain) { - callback(new Error('domain is required')); - return; + /** + * Get a single sending domain, by domain + * + * @param {string} domain - The domain name to get + * @param {RequestCb} [callback] + * @return {Promise} + */ + get: function(domain, callback) { + let options; + + if (!domain || typeof domain === 'function') { + return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; - client.get(options, callback); - }, - create: function (domainBody, callback) { - if(typeof domainBody === 'function') { - callback = domainBody; - domainBody = null; - } - if(!domainBody) { - callback(new Error('domainBody is required')); - return; - } + return client.get(options).asCallback(callback); + }, - if(!domainBody.domain) { - callback(new Error('domain is required in the domainBody')); - return; + /** + * Creates a new sending domain + * + * @param {Object} createOpts - attributes used to create the new domain + * @param {RequestCb} [callback] + * @return {Promise} + */ + create: function(createOpts, callback) { + let options; + + if (!createOpts || typeof createOpts !== 'object') { + return Promise.reject(new Error('create options are required')).asCallback(callback); } - var options = { - uri: api - , json: toApiFormat(domainBody) + options = { + uri: api, + json: createOpts }; - client.post(options, callback); + + return client.post(options).asCallback(callback); }, - update: function (domainBody, callback) { - if(typeof domainBody === 'function') { - callback = domainBody; - domainBody = null; - } - if(!domainBody) { - callback(new Error('domainBody is required')); - return; + /** + * Update an existing sending domain + * + * @param {string} domain - The domain to update + * @param {Object} updateOpts - Hash of the sending domain attributes to update + * @param {RequestCb} [callback] + * @return {Promise} + */ + update: function(domain, updateOpts, callback) { + let options; + + if (typeof domain !== 'string') { + return Promise.reject(new Error('domain is required')).asCallback(callback); } - if(!domainBody.domain) { - callback(new Error('domain is required in the domainBody')); - return; + if (!updateOpts || typeof updateOpts !== 'object') { + return Promise.reject(new Error('update options are required')).asCallback(callback); } - var obj = toApiFormat(domainBody); - var options = { - uri: api + '/' + obj.domain - , json: toApiFormat(domainBody) + options = { + uri: api + '/' + domain, + json: updateOpts }; - client.put(options, callback); + + return client.put(options).asCallback(callback); }, + + /** + * Delete an existing sending domain + * + * @param {string} domain - The domain to delete + * @param {RequestCb} [callback] + * @return {Promise} + */ delete: function(domain, callback) { - if (typeof domain === 'function') { - callback = domain; - domain = null; - } + let options; - if (!domain) { - callback(new Error('domain is required')); - return; + if (typeof domain !== 'string') { + return Promise.reject(new Error('domain is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + domain }; - client.delete(options, callback); + + return client.delete(options).asCallback(callback); }, - verify: function (options, callback) { - options = options || {}; - if(!options.domain) { - callback(new Error('domain is required')); - return; + /** + * Verify an existing sending domain + * + * @param {string} domain - The domain to verify + * @param {Object} options - Hash of options to include in verification request + * @param {RequestCb} [callback] + * @return {Promise} + */ + verify: function(domain, options, callback) { + let reqOpts; + + if (typeof domain !== 'string') { + return Promise.reject(new Error('domain is required')).asCallback(callback); + } + + if (!options || typeof options !== 'object') { + return Promise.reject(new Error('verification options are required')).asCallback(callback); } - var reqOpts = { - uri: api + '/' + options.domain + '/verify', - json: { - dkim_verify: options.verifyDKIM !== false, - spf_verify: options.verifySPF !== false - } + reqOpts = { + uri: api + '/' + domain + '/verify', + json: options }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); } }; - return sendingDomains; }; diff --git a/lib/sparkpost.js b/lib/sparkpost.js index 3f59e1a..67f1b2c 100644 --- a/lib/sparkpost.js +++ b/lib/sparkpost.js @@ -1,24 +1,27 @@ 'use strict'; -var version = require( '../package.json').version +var version = require('../package.json').version , url = require('url') - , request = require( 'request') - , _ = require( 'lodash' ); + , Promise = require('./Promise') + , request = require('request') + , _ = require('lodash') + , defaults, resolveUri, handleOptions, createSparkPostError, SparkPost; //REST API Config Defaults -var defaults = { +defaults = { origin: 'https://api.sparkpost.com:443', - apiVersion: 'v1' + apiVersion: 'v1', + debug: false }; -var resolveUri = function(origin, uri) { - if(!/^http/.test(uri)) { +resolveUri = function(origin, uri) { + if (!/^http/.test(uri)) { uri = url.resolve(origin, uri); } return uri; }; -var handleOptions = function(apiKey, options) { +handleOptions = function(apiKey, options) { if (typeof apiKey === 'object') { options = apiKey; options.key = process.env.SPARKPOST_API_KEY; @@ -32,13 +35,23 @@ var handleOptions = function(apiKey, options) { return options; }; -var SparkPost = function(apiKey, options) { +createSparkPostError = function(res, body) { + var err = new Error(res.statusMessage); + body = body || {}; + err.name = 'SparkPostError'; + err.errors = body.errors; + err.statusCode = res.statusCode; + + return err; +}; + +SparkPost = function(apiKey, options) { options = handleOptions(apiKey, options); this.apiKey = options.key || process.env.SPARKPOST_API_KEY; - if(typeof this.apiKey === 'undefined') { + if (typeof this.apiKey === 'undefined') { throw new Error('Client requires an API Key.'); } @@ -54,6 +67,7 @@ var SparkPost = function(apiKey, options) { //Optional client config this.origin = options.origin; this.apiVersion = options.apiVersion || defaults.apiVersion; + this.debug = (typeof options.debug === 'boolean') ? options.debug : defaults.debug; this.inboundDomains = require('./inboundDomains')(this); this.messageEvents = require('./messageEvents')(this); @@ -67,17 +81,18 @@ var SparkPost = function(apiKey, options) { this.webhooks = require('./webhooks')(this); }; -SparkPost.prototype.request = function( options, callback ) { +SparkPost.prototype.request = function(options, callback) { + var baseUrl; // we need options - if(!_.isPlainObject(options)) { - throw new TypeError( 'options argument is required' ); + if (!_.isPlainObject(options)) { + throw new TypeError('options argument is required'); } - var baseUrl = this.origin + '/api/' + this.apiVersion + '/'; + baseUrl = this.origin + '/api/' + this.apiVersion + '/'; // if we don't have a fully qualified URL let's make one - options.uri = resolveUri( baseUrl, options.uri ); + options.uri = resolveUri(baseUrl, options.uri); // merge headers options.headers = _.merge({}, this.defaultHeaders, options.headers); @@ -93,47 +108,61 @@ SparkPost.prototype.request = function( options, callback ) { options.gzip = true; } - request(options, function(err, res, body) { - var invalidCodeRegex = /(5|4)[0-9]{2}/; - if(err) { - return callback(err, res); - } else if(invalidCodeRegex.test(res.statusCode)) { - body = body || {}; - err = new Error(res.statusMessage); - err.name = 'SparkPostError'; - err.errors = body.errors; - err.statusCode = res.statusCode; - return callback(err, res); - } else { - return callback(null, res); - } - }); + // set debug + options.debug = (typeof options.debug === 'boolean') ? options.debug : this.debug; + + return new Promise(function(resolve, reject) { + request(options, function(err, res, body) { + var invalidCodeRegex = /(5|4)[0-9]{2}/ + , response; + + if (err) { + reject(err); + } else if (invalidCodeRegex.test(res.statusCode)) { + err = createSparkPostError(res, body); + reject(err); + } else { + response = body; + if (options.debug) { + response.debug = res; + } + resolve(response); + } + }); + }).asCallback(callback); }; -SparkPost.prototype.get = function( options, callback ) { +SparkPost.prototype.get = function(options, callback) { options.method = 'GET'; + options.json = true; - this.request(options, callback); + return this.request(options).asCallback(callback); }; -SparkPost.prototype.post = function( options, callback ) { +SparkPost.prototype.post = function(options, callback) { options.method = 'POST'; - this.request(options, callback); + return this.request(options).asCallback(callback); }; -SparkPost.prototype.put = function( options, callback ) { +SparkPost.prototype.put = function(options, callback) { options.method = 'PUT'; - this.request(options, callback); + return this.request(options).asCallback(callback); }; -SparkPost.prototype['delete'] = function( options, callback ) { +SparkPost.prototype.delete = function(options, callback) { options.method = 'DELETE'; - this.request(options, callback); + return this.request(options).asCallback(callback); }; -SparkPost.SendGridCompatibility = require('./SendGridCompatibility'); - module.exports = SparkPost; + +/** + * Standard error-first callback for HTTP requests + + * @callback RequestCb + * @param {Error} err - Any error that occurred + * @param {Object} [data] - API response body (or just the value of `body.results`, if it exists) + */ diff --git a/lib/subaccounts.js b/lib/subaccounts.js index 85de232..f4f9cf5 100644 --- a/lib/subaccounts.js +++ b/lib/subaccounts.js @@ -1,115 +1,86 @@ 'use strict'; -var api = 'subaccounts'; - -var toApiFormat = function(input) { - var model = {}; - - model.name = input.name; - model.key_label = input.keyLabel; - model.ip_pool = input.ipPool; - model.status = input.status; - - model.key_grants = Array.isArray(input.keyGrants) ? input.keyGrants : [input.keyGrants]; - - // server returns 500 if key_valid_ips is empty array - if (input.keyValidIps) { - var keyValidIpsIsArray = Array.isArray(input.keyValidIps); - if (keyValidIpsIsArray && input.keyValidIps.length > 0) { - model.key_valid_ips = input.keyValidIps; - } else if (!keyValidIpsIsArray) { - model.key_valid_ips = [input.keyValidIps]; - } - } - - return model; -}; - -var validateCreateOptions = function(input) { - if (!input.name) { - return 'name is required'; - } - - if (!input.keyLabel) { - return 'keyLabel is required'; - } - - if (!input.keyGrants) { - return 'keyGrants is required'; - } - - return null; -}; +const Promise = require('./Promise'); +const api = 'subaccounts'; module.exports = function(client) { var subaccounts = { - all: function(callback) { - var options = { + /** + * List a summary of all subaccounts + * + * @param {RequestCb} [callback] + * @return {Promise} + */ + list: function(callback) { + let options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - find: function(subaccountId, callback) { - if(typeof subaccountId === 'function') { - callback = subaccountId; - subaccountId = null; - } - - if (!subaccountId) { - callback(new Error('subaccountId is required')); - return; + /** + * Get details about a specified subaccount by its id + * + * @param {string} id - the id of the subaccount you want to look up + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(id, callback) { + var options; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - var options = { - uri: api + '/' + subaccountId + options = { + uri: api + '/' + id }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - create: function(options, callback) { - if(typeof options === 'function') { - callback = options; - options = null; - } - - if (!options) { - callback(new Error('options are required')); - return; + /** + * Create a new subaccount + * + * @param subaccount - an object of [subaccount attributes]{https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes} + * @param {RequestCb} [callback] + * @returns {Promise} + */ + create: function(subaccount, callback) { + var reqOpts; + + if (!subaccount || typeof subaccount !== 'object') { + return Promise.reject(new Error('subaccount object is required')).asCallback(callback); } - var validation = validateCreateOptions(options); - if (validation) { - callback(new Error(validation + ' in options')); - return; - } - - var reqOpts = { + reqOpts = { uri: api, - json: toApiFormat(options) + json: subaccount }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - if(typeof options === 'function') { - callback = options; - options = null; + /** + * Update existing subaccount by id + * + * @param {string} id - the id of the subaccount you want to update + * @param {Object} subaccount - an object of [subaccount attributes]{https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1} + * @param {RequestCb} callback + * @returns {Promise} + */ + update: function(id, subaccount, callback) { + var reqOpts; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!options) { - callback(new Error('options are required')); - return; + if (!subaccount || typeof subaccount !== 'object') { + return Promise.reject(new Error('subaccount object is required')).asCallback(callback); } - if(!options.subaccountId) { - callback(new Error('subaccountId is required in options')); - return; - } - - var subaccountId = options.subaccountId; - var reqOpts = { - uri: api + '/' + subaccountId, - json: toApiFormat(options) + reqOpts = { + uri: api + '/' + id, + json: subaccount }; - client.put(reqOpts, callback); + + return client.put(reqOpts).asCallback(callback); } }; diff --git a/lib/suppressionList.js b/lib/suppressionList.js index aa130a9..7d4f985 100644 --- a/lib/suppressionList.js +++ b/lib/suppressionList.js @@ -1,74 +1,92 @@ 'use strict'; -var api = 'suppression-list' - , toApiFormat = require('./toApiFormat'); +const Promise = require('./Promise'); +const api = 'suppression-list'; module.exports = function(client) { return { - search: function(parameters, callback) { - var options = { + /** + * Lists all entries in your suppression list, + * filtered by an optional set of parameters + * + * @param {Object} [parameters] - Hash of parameters to filter results + * @param {RequestCb} [callback] + * @return {Promise} + */ + list: function(parameters, callback) { + let options = { uri: api , qs: parameters }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - checkStatus: function(email, callback) { - if(typeof email === 'function') { - callback = email; - email = null; - } - if(!email) { - callback(new Error('email is required')); - return; + /** + * Gets a single entry by email address ID + * + * @param {String} email + * @param {RequestCb} [callback] + * @return {Promise} + */ + get: function(email, callback) { + let options; + + if (!email || typeof email === 'function') { + return Promise.reject(new Error('email is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + email }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - removeStatus: function(email, callback) { - if(typeof email === 'function') { - callback = email; - email = null; + + /** + * Updates existing entries, or creates entries + * if they don't exist for that email address ID + * + * @param {Array|Object} listEntries - List of suppression entry objects to upsert + * @param {RequestCb} [callback] + * @return {Promise} + */ + upsert: function(listEntries, callback) { + let options; + + if (!listEntries || typeof listEntries === 'function') { + return Promise.reject(new Error('list entries is required')).asCallback(callback); } - if(!email) { - callback(new Error('email is required')); - return; + if (!Array.isArray(listEntries)) { + listEntries = [listEntries]; } - var options = { - uri: api + '/' + email + options = { + uri: api, + json: { recipients: listEntries } }; - client['delete'](options, callback); - }, - upsert: function(recipients, callback) { - var options; - if(typeof recipients === 'function') { - callback = recipients; - recipients = null; - } + return client.put(options, callback).asCallback(callback); + }, - if(!recipients) { - callback(new Error('recipient is required')); - return; - } + /** + * Deletes a single entry, by email address ID + * + * @param {String} email + * @param {RequestCb} [callback] + * @return {Promise} + */ + delete: function(email, callback) { + let options; - if(!Array.isArray(recipients)) { - recipients = [recipients]; + if (!email || typeof email === 'function') { + return Promise.reject(new Error('email is required')).asCallback(callback); } - recipients = toApiFormat(recipients); options = { - uri: api, - json: { recipients: recipients } + uri: api + '/' + email }; - - client.put(options, callback); + return client.delete(options).asCallback(callback); } }; diff --git a/lib/templates.js b/lib/templates.js index b80dbe3..3e879dd 100644 --- a/lib/templates.js +++ b/lib/templates.js @@ -1,111 +1,154 @@ 'use strict'; -var api = 'templates' - , toApiFormat = require('./toApiFormat'); +const api = 'templates'; +const Promise = require('./Promise'); +const _ = require('lodash'); module.exports = function(client) { - var templates = { - all: function(callback) { + return { + /** + * List an overview of all templates. + * + * @param {RequestCb} [callback] + * @returns {Promise} + */ + list: function(callback) { var options = { uri: api }; - client.get(options, callback); + return client.get(options).asCallback(callback); }, - find: function(options, callback) { + /** + * Get details about a specified template by its id. + * + * @param {string} id + * @param {Object} options + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(id, options, callback) { + var reqOpts; options = options || {}; - if(!options.id) { - callback(new Error('template id is required')); - return; + if (!id) { + return Promise.reject(new Error('template id is required')).asCallback(callback); } - var reqOpts = { - uri: api + '/' + options.id + reqOpts = { + uri: api + '/' + id + , qs: options }; - if(options.draft) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.draft = options.draft; - } - - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - create: function(options, callback) { - options = options || {}; - - if (!options.template) { - callback(new Error('template object is required')); - return; + /** + * Create a new template. + * + * @param {Object} template + * @param {RequestCb} [callback] + * @returns {Promise} + */ + create: function(template, callback) { + var reqOpts; + + if (!template || typeof template !== 'object') { + return Promise.reject(new Error('template object is required')).asCallback(callback); } - var reqOpts = { + reqOpts = { uri: api - , json: toApiFormat(options.template) + , json: template }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, - update: function(options, callback) { - options = options || {}; + /** + * Update an existing template. + * + * @param {String} id + * @param {Object} template + * @param {Object} options + * @param {RequestCb} callback + * @returns {Promise} + */ + update: function(id, template, options, callback) { + var reqOpts; + + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; + } - if(!options.template) { - callback(new Error('template object is required')); - return; + if (!id) { + return Promise.reject(new Error('template id is required')).asCallback(callback); } - var object = toApiFormat(options.template) - , reqOpts = { - uri: api + '/' + object.id - , json: object - }; + if (!template || typeof template !== 'object') { + return Promise.reject(new Error('template object is required')).asCallback(callback); + } - if(options.update_published) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.update_published = options.update_published; + reqOpts = { + uri: api + '/' + id + , json: template + , qs: options + }; + + return client.put(reqOpts).asCallback(callback); + }, + /** + * Delete an existing template. + * + * @param {String} id + * @param {RequestCb} [callback] + * @returns {Promise} + */ + delete: function(id, callback) { + var options; + + if (!id || typeof id !== 'string') { + return Promise.reject(new Error('template id is required')).asCallback(callback); } - client.put(reqOpts, callback); + options = { + uri: api + '/' + id + }; + return client.delete(options).asCallback(callback); }, - preview: function(options, callback) { + /** + * Preview the most recent version of an existing template by id. + * + * @param {String} id + * @param {Object} options + * @param {RequestCb} [callback] + * @returns {Promise} + */ + preview: function(id, options, callback) { + var reqOpts; options = options || {}; - if(!options.id) { - callback(new Error('template id is required')); - return; + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; } - var reqOpts = { - uri: api + '/' + options.id + '/preview' - , json: { - substitution_data: options.data - } - }; - - if (options.draft) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.draft = options.draft; + if (!id) { + return Promise.reject(new Error('template id is required')).asCallback(callback); } - client.post(reqOpts, callback); - } - }; + reqOpts = { + uri: api + '/' + id + '/preview' + , json: _.cloneDeep(options) + , qs: {} + }; - templates['delete'] = function(id, callback) { - if (typeof id === 'function') { - callback = id; - id = null; - } + if (reqOpts.json.draft) { + reqOpts.qs.draft = reqOpts.json.draft; + delete reqOpts.json.draft; + } - if (!id) { - callback(new Error('template id is required')); - return; + return client.post(reqOpts).asCallback(callback); } - - var options = { - uri: api + '/' + id - }; - client['delete'](options, callback); }; - - return templates; }; diff --git a/lib/toApiFormat.js b/lib/toApiFormat.js deleted file mode 100644 index 3f33a46..0000000 --- a/lib/toApiFormat.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; -var _ = require('lodash') - , pointer = require('json-pointer'); - -var excludeList = [ - '/substitution_data', - '/tags', - '/metadata', - '/attributes', - '/headers', - '/content/email_rfc822' -]; - -function snakedKeyClone(source) { - if (!_.isObject(source)) { - return source; - } - - var target = Array.isArray(source) ? [] : {}; - - Object.keys(source).forEach(function(key) { - target[_.snakeCase(key)] = snakedKeyClone(source[key]); - }); - - return target; -} - -module.exports = function toApiFormat(source) { - - var excludedObjects = {}; - - // Look in the source object for the excluded pointers and take a copy of the - // objects pointed to by those keys. Then remove them from the source object. - excludeList.forEach(function(exclusionPointer) { - if (pointer.has(source, exclusionPointer)) { - pointer.set(excludedObjects, exclusionPointer, pointer.get(source, exclusionPointer)); - pointer.remove(source, exclusionPointer); - } - }); - - // Make a clone of the remaining source object but with snaked case keys - var target = snakedKeyClone(source); - - // Reinstated the un-modified objects into the target - excludeList.forEach(function(exclusionPointer) { - if (pointer.has(excludedObjects, exclusionPointer)) { - pointer.set(target, exclusionPointer, pointer.get(excludedObjects, exclusionPointer)); - } - }); - - return target; -}; diff --git a/lib/transmissions.js b/lib/transmissions.js index b7317ec..0625780 100644 --- a/lib/transmissions.js +++ b/lib/transmissions.js @@ -1,7 +1,7 @@ 'use strict'; -var api = 'transmissions' - , toApiFormat = require('./toApiFormat'); +const api = 'transmissions'; +const Promise = require('./Promise'); /* * "Class" declaration, Transmissions exposes three functions, one for sending a transmission, @@ -11,66 +11,77 @@ var api = 'transmissions' module.exports = function(client) { return { - send: function (options, callback) { - options = options || {}; - - if(!options.transmissionBody) { - callback(new Error('transmissionBody is required')); - return; + /** + * List an overview of all transmissions in the account + * + * @param {Object} options + * @param {RequestCb} [callback] + * @returns {Promise} + */ + list: function(options, callback) { + var reqOpts; + + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; } - var mappedInput = toApiFormat(options.transmissionBody); - - var reqOpts = { + reqOpts = { uri: api, - json: mappedInput + qs: options }; - if (options.num_rcpt_errors) { - reqOpts.qs = reqOpts.qs || {}; - reqOpts.qs.num_rcpt_errors = options.num_rcpt_errors; - delete options.num_rcpt_errors; - } - - client.post(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - all: function (options, callback) { - if(typeof options === 'function') { - callback = options; - options = {}; + /** + * Retrieve the details about a transmission by its id + * + * @param {String} id + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(id, callback) { + var options; + + if (typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - var reqOpts = { - uri: api, - qs: {} + options = { + uri: api + '/' + id }; - if (options.campaign_id) { - reqOpts.qs.campaign_id = options.campaign_id; + return client.get(options).asCallback(callback); + }, + /** + * Sends a message by creating a new transmission + * + * @param {Object} transmission + * @param {Object} options + * @param {RequestCb} [callback] + * @returns {Promise} + */ + send: function(transmission, options, callback) { + var reqOpts; + + if (!transmission || typeof transmission !== 'object') { + return Promise.reject(new Error('transmission object is required')).asCallback(callback); } - if (options.template_id) { - reqOpts.qs.template_id = options.template_id; + // Handle optional options argument + if (typeof options === 'function') { + callback = options; + options = {}; } - client.get(reqOpts, callback); - }, - find: function (transmissionID, callback) { - var options = { - uri: api + '/' + transmissionID + reqOpts = { + uri: api, + json: transmission, + qs: options }; - if(typeof transmissionID === 'function') { - callback = transmissionID; - transmissionID = null; - } - - if(!transmissionID) { - callback(new Error('transmissionID is required')); - return; - } - - client.get(options, callback); + return client.post(reqOpts).asCallback(callback); } }; diff --git a/lib/webhooks.js b/lib/webhooks.js index c590ed8..76dd824 100644 --- a/lib/webhooks.js +++ b/lib/webhooks.js @@ -1,173 +1,241 @@ 'use strict'; -var api = 'webhooks' - , toApiFormat = require('./toApiFormat'); +const Promise = require('./Promise'); +const api = 'webhooks'; module.exports = function(client) { - var webhooks = { - all: function (options, callback) { + return { + + /** + * Lists all webhooks + * + * @param {Object} [options] - Hash of options + * @param {string} [options.timezone] - The timezone to use for the last_successful and last_failure properties. + * @param {RequestCb} [callback] + * @returns {Promise} + */ + list: function(options, callback) { var reqOpts = { - uri: api + uri: api, + qs: {} }; - if (typeof options === 'function') { + if (!options || typeof options === 'function') { callback = options; options = {}; } if (options.timezone) { - reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.timezone = options.timezone; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - describe: function (options, callback) { - options = options || {}; - if (!options.id) { - callback(new Error('id is required')); - return; + /** + * Get a single webhook by ID + * + * @param {string} id - The ID of the webhook to get + * @param {Object} [options] - Hash of options + * @param {string} [options.timezone] - The timezone to use for the last_successful and last_failure properties. + * @param {RequestCb} [callback] + * @returns {Promise} + */ + get: function(id, options, callback) { + var reqOpts; + + if (!options || typeof options === 'function') { + callback = options; + options = {}; } - var reqOpts = { - uri: api + '/' + options.id + + if (typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); + } + + reqOpts = { + uri: api + '/' + id, + qs: {} }; if (options.timezone) { - reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.timezone = options.timezone; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - create: function (webhook, callback) { - if (typeof webhook === 'function') { - callback = webhook; - webhook = null; - } - if (!webhook) { - callback(new Error('webhook object is required')); - return; + /** + * Creates a new webhook + * + * @param {Object} webhook - attributes used to create the new webhook + * @param {RequestCb} [callback] + * @returns {Promise} + */ + create: function(webhook, callback) { + var options; + + if (!webhook || typeof webhook === 'function') { + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - var options = { - uri: api - , json: toApiFormat(webhook) + + options = { + uri: api, + json: webhook }; - client.post(options, callback); + return client.post(options).asCallback(callback); }, - update: function (webhook, callback) { - var object, options, id; - - if (typeof webhook === 'function') { - callback = webhook; - webhook = null; - } - if (!webhook) { - callback(new Error('webhook object is required')); - return; + /** + * Update an existing webhook + * + * @param {string} id - The ID of the webhook to update + * @param {Object} webhook - Hash of the webhook attributes to update + * @param {RequestCb} [callback] + * @returns {Promise} + */ + update: function(id, webhook, callback) { + var options; + if (!id) { + return Promise.reject(new Error('id is required')).asCallback(callback); } - if (!webhook.id) { - callback(new Error('webhook.id is required')); - return; + if (!webhook || typeof webhook === 'function') { + return Promise.reject(new Error('webhook object is required')).asCallback(callback); } - id = webhook.id; - delete webhook.id; - - object = toApiFormat(webhook); options = { - uri: api + '/' + id - , json: object + uri: api + '/' + id, + json: webhook }; - client.put(options, callback); + delete options.json.id; + + return client.put(options).asCallback(callback); }, - delete: function (id, callback) { - if (typeof id === 'function') { - callback = id; - id = null; - } - if (!id) { - callback(new Error('id is required')); - return; + /** + * Delete an existing webhook + * + * @param {string} id - The ID of the webhook to delete + * @param {RequestCb} [callback] + * @returns {Promise} + */ + delete: function(id, callback) { + var options; + + if (!id || typeof id === 'function') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - var options = { + options = { uri: api + '/' + id }; - client.delete(options, callback); + return client.delete(options).asCallback(callback); }, - validate: function(options, callback) { - options = options || {}; - if(!options.id) { - callback(new Error('id is required')); - return; + /** + * Sends an example message event batch from the Webhook API to the target URL. + * + * @param {string} id - The ID of the webhook to validate + * @param {Object} options - Hash of options used to validate the webhook + * @param {string} options.message - The message (payload) to send to the webhook consumer. + * @param {RequestCb} [callback] + * @returns {Promise} + */ + validate: function(id, options, callback) { + var reqOpts; + + if (typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); } - if(!options.message) { - callback(new Error('message is required')); - return; + if (!options || typeof options === 'function' || !options.message) { + return Promise.reject(new Error('message is required')).asCallback(callback); } - var reqOpts = { - uri: api + '/' + options.id + '/validate' - , json: { + reqOpts = { + uri: api + '/' + id + '/validate', + json: { message: options.message } }; - client.post(reqOpts, callback); + return client.post(reqOpts).asCallback(callback); }, - getBatchStatus: function(options, callback) { - options = options || {}; - if(!options.id) { - callback(new Error('id is required')); - return; + /** + * Gets recent status information about a webhook. + * + * @param {string} id - The ID of the webhook to check + * @param {Object} [options] - Hash of options + * @param {string} [options.limit] - The maximum number of results to return. + * @param {RequestCb} [callback] + * @returns {Promise} + */ + getBatchStatus: function(id, options, callback) { + var reqOpts; + + if (!options || typeof options === 'function') { + callback = options; + options = {}; } - var reqOpts = { - uri: api + '/' + options.id + '/batch-status' + if (typeof id !== 'string') { + return Promise.reject(new Error('id is required')).asCallback(callback); + } + + reqOpts = { + uri: api + '/' + id + '/batch-status', + qs: {} }; if (options.limit) { - reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.limit = options.limit; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, + + /** + * Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. + * + * @param {RequestCb} [callback] + * @returns {Promise} + */ getDocumentation: function(callback) { var reqOpts = { uri: api + '/events/documentation' }; - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); }, - getSamples: function(options, callback){ + + /** + * Lists examples of the event data that will be posted to a webhook consumer. + * + * @param {Object} [options] - Hash of options + * @param {string} [options.events] - A comma delimited list of events to get samples of. + * @param {RequestCb} [callback] + * @returns {Promise} + */ + getSamples: function(options, callback) { var reqOpts = { - uri: api + '/events/samples' + uri: api + '/events/samples', + qs: {} }; - if (typeof options === 'function') { + if (!options || typeof options === 'function') { callback = options; options = {}; } if (options.events) { - reqOpts.qs = reqOpts.qs || {}; reqOpts.qs.events = options.events; } - client.get(reqOpts, callback); + return client.get(reqOpts).asCallback(callback); } }; - - return webhooks; }; diff --git a/package.json b/package.json index 05f8268..f4bd59e 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,10 @@ "description": "A Node.js wrapper for interfacing with your favorite SparkPost APIs", "main": "./lib/sparkpost.js", "scripts": { - "test": "grunt", - "ci": "grunt && grunt coveralls:grunt_coveralls_coverage" + "coveralls": "cat ./test/reports/lcov.info | coveralls", + "pretest": "eslint lib/**", + "test": "istanbul cover --report lcov --dir test/reports/ _mocha --recursive ./test/spec --grep ./test/**/*.spec.js -- --colors --reporter spec", + "postversion": "git push upstream && git push --tags upstream" }, "keywords": [ "email", @@ -22,26 +24,20 @@ }, "homepage": "https://github.com/SparkPost/node-sparkpost", "devDependencies": { - "chai": "1.9.1", - "grunt": "0.4.5", - "grunt-bump": "^0.3.1", - "grunt-contrib-jshint": "0.10.0", - "grunt-coveralls": "^1.0.0", - "grunt-shell": "1.1.1", - "istanbul": "0.3.2", - "jshint-stylish": "0.4.0", - "matchdep": "0.3.0", - "mocha": "1.21.4", - "nock": "^7.2.2", - "proxyquire": "1.0.1", - "sinon": "^1.14.1", - "sinon-chai": "2.5.0", - "time-grunt": "1.0.0", - "xunit-file": "0.0.5" + "chai": "^3.5.0", + "chai-as-promised": "^6.0.0", + "coveralls": "^2.11.12", + "eslint": "^3.3.1", + "eslint-config-sparkpost": "^1.2.0", + "istanbul": "^0.4.5", + "mocha": "^3.0.2", + "nock": "^9.0.0", + "sinon": "^1.17.5", + "sinon-as-promised": "^4.0.2", + "sinon-chai": "^2.8.0" }, "dependencies": { - "json-pointer": "^0.5.0", "lodash": "^4.13.1", - "request": "^2.72.0" + "request": "^2.74.0" } } diff --git a/test/spec/SendGridCompatibility/Email.spec.js b/test/spec/SendGridCompatibility/Email.spec.js deleted file mode 100644 index d995c8e..0000000 --- a/test/spec/SendGridCompatibility/Email.spec.js +++ /dev/null @@ -1,154 +0,0 @@ -var chai = require('chai') - , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , email = require('../../../lib/SendGridCompatibility/Email'); - -chai.use(sinonChai); - -describe('SendGrid Email Object', function() { - var tmpEmail - , payload = { - to: ['fake@email.org', 'real@notreally.net'], - toname: ['Fakey Fakerson', 'Realy Realerson'], - from: 'a.sender@company.com', - fromname: 'A. Sender', - subject: 'Sale', - text: 'Look at this sale!', - html: '

Look

at this sale!
', - bcc: ['bcc@bbc.co.uk', 'bcc@cbc.ca'], - replyto: 'a.replyto@company.com', - date: new Date(), - files: [ - { - filename: 'name.txt', - path: '../../../../../../', - url: 'www.google.com', - content: '?' - } - ], - file_data: {asdf: 'asdf'}, - headers: {asdfasdf: 'asdfasdf'} - }; - - describe('instantiation', function() { - it('should handle empty input', function() { - tmpEmail = new email(); - expect(Object.keys(tmpEmail).length).to.equal(0); - }); - it('should handle a payload', function() { - tmpEmail = new email(payload); - for (var index in tmpEmail) { - if(typeof tmpEmail[index] !== 'function'){ - expect(tmpEmail[index]).to.deep.equal(payload[index]); - } - } - }); - }); - - describe('compatibility functions: ', function() { - beforeEach(function() { - tmpEmail = new email(payload); - }); - it('addTo', function() { - tmpEmail.to = undefined; - tmpEmail.addTo('fake@email.org'); - tmpEmail.addTo('real@notreally.net'); - tmpEmail.addTo('asdf@asdf.com'); - expect(tmpEmail.to).to.deep.equal(['fake@email.org','real@notreally.net','asdf@asdf.com']); - }); - it('setFrom', function(){ - tmpEmail.setFrom('email@email.edu'); - expect(tmpEmail.from).to.equal('email@email.edu'); - }); - it('setSubject', function(){ - tmpEmail.setSubject('new subject'); - expect(tmpEmail.subject).to.equal('new subject'); - }); - it('setText', function(){ - tmpEmail.setText('new text'); - expect(tmpEmail.text).to.equal('new text'); - }); - it('setHtml', function(){ - tmpEmail.setHtml('

new html

'); - expect(tmpEmail.html).to.equal('

new html

'); - }); - it('addHeader', function(){ - tmpEmail.headers = undefined; - tmpEmail.addHeader('abcd', 'efgh'); - tmpEmail.addHeader('1234', '5678'); - expect(tmpEmail.headers).to.deep.equal({abcd: 'efgh', 1234: '5678'}); - }); - it('setHeaders', function(){ - tmpEmail.setHeaders({oldish: 'new'}); - expect(tmpEmail.headers).to.deep.equal({oldish: 'new'}); - }); - it('addSubstitution', function(){ - tmpEmail.addSubstitution('key', 'value'); - tmpEmail.addSubstitution('attributeName', ['attribute1', 'attribute2']); - expect(tmpEmail.sub).to.deep.equal({key: ['value'], attributeName: ['attribute1', 'attribute2']}); - }); - it('setSubstitutions', function(){ - tmpEmail.setSubstitutions({index: ['element']}); - expect(tmpEmail.sub).to.deep.equal({index: ['element']}); - }); - it('addSection', function(){ - tmpEmail.addSection('key', 'value'); - tmpEmail.addSection('attributeName', 'attribute1'); - expect(tmpEmail.section).to.deep.equal({key: 'value', attributeName: 'attribute1'}); - }); - it('setSections', function(){ - tmpEmail.setSections({index: 'element'}); - expect(tmpEmail.section).to.deep.equal({index: 'element'}); - }); - it('addUniqueArg', function(){ - try { - tmpEmail.addUniqueArg(); - } catch (err) { - expect(err).to.deep.equal(new Error('Unique Argument compatibility is not supported.')); - } - }); - it('setUniqueArgs', function(){ - try { - tmpEmail.setUniqueArgs(); - } catch (err) { - expect(err).to.deep.equal(new Error('Unique Argument compatibility is not supported.')); - } - }); - it('addCategory', function(){ - try { - tmpEmail.addCategory(); - } catch (err) { - expect(err).to.deep.equal(new Error('Category compatibility is not supported.')); - } - }); - it('setCategories', function(){ - try { - tmpEmail.setCategories(); - } catch (err) { - expect(err).to.deep.equal(new Error('Category compatibility is not supported.')); - } - }); - it('addFilter', function(){ - try { - tmpEmail.addFilter(); - } catch (err) { - expect(err).to.deep.equal(new Error('Filter compatibility is not supported.')); - } - }); - it('setFilters', function(){ - try { - tmpEmail.setFilters(); - } catch (err) { - expect(err).to.deep.equal(new Error('Filter compatibility is not supported.')); - } - }); - it('addFile', function(){ - try { - tmpEmail.addFile(); - } catch (err) { - expect(err).to.deep.equal(new Error('File compatibility is not supported.')); - } - }); - }); -}); diff --git a/test/spec/SendGridCompatibility/index.spec.js b/test/spec/SendGridCompatibility/index.spec.js deleted file mode 100644 index 52bd367..0000000 --- a/test/spec/SendGridCompatibility/index.spec.js +++ /dev/null @@ -1,137 +0,0 @@ -var chai = require('chai') - , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , nock = require('nock') - , sendGridCompatibility = require('../../../lib/SendGridCompatibility'); - -chai.use(sinonChai); - -describe('SendGrid Compatibility', function() { - var sendgrid = new sendGridCompatibility('asdf', 'asdf') - , transmissions = sendgrid.client.transmissions - , payload = { - to: ['fake@email.org', 'real@notreally.net'], - toname: ['Fakey Fakerson', 'Realy Realerson'], - from: 'a.sender@company.com', - fromname: 'A. Sender', - subject: 'Sale', - text: 'Look at this sale!', - html: '

Look

at this sale!
', - bcc: ['bcc@bbc.co.uk', 'bcc@cbc.ca'], - replyto: 'a.replyto@company.com', - date: new Date(), - files: [ - { - filename: 'name.txt', - path: '../../../../../../', - url: 'www.google.com', - content: '?' - } - ], - file_data: {asdf: 'asdf'}, - headers: {asdfasdf: 'asdfasdf'}, - sub: {password: ['******'], num: ['one', 'two']}, - section: {something: 'something else'} - }, - translatedPayload = { - recipients: [ - { - address: { - email: 'fake@email.org', - name: 'Fakey Fakerson' - } - }, - { - address: { - email: 'real@notreally.net', - name: 'Realy Realerson' - } - } - ], - from: 'a.sender@company.com ', - html: '

Look

at this sale!
', - text: 'Look at this sale!', - subject: 'Sale', - replyTo: 'a.replyto@company.com', - customHeaders: {asdfasdf: 'asdfasdf'}, - substitutionData: { - password: [ '******' ], - num: [ 'one', 'two' ], - something: 'something else' - } - }; - - describe('Instantiation', function() { - it('should expose a send function', function() { - expect(sendgrid.send).to.be.a.function; - }); - - it('should handle building an endpoint from options', function() { - var sendgrid = new sendGridCompatibility('as', 'df', {port: '5000', host: 'test.sparkpost.com', protocol: 'http'}); - expect(sendgrid.client.origin).to.equal('http://test.sparkpost.com:5000'); - }); - }); - - describe('send Method', function() { - var sendSpy, scope; - - beforeEach(function() { - sendSpy = sinon.spy(transmissions, 'send'); - scope = nock('https://api.sparkpost.com') - .post('/api/v1/transmissions') - .reply(200, { ok: true }); - }); - - afterEach(function() { - transmissions.send.restore(); // restoring function - }); - - it('should handle an absence of toname', function(done) { - var toPayload = {to: 'asdf@qwerty.lg.jp'}; - sendgrid.send(toPayload, function() { - expect(sendSpy.args[0][0].transmissionBody.recipients).to.deep.equal([{ address: { email: 'asdf@qwerty.lg.jp' }}]); - done(); - }); - }); - - it('should translate only substitutions into substitutionData appropriately', function(done) { - var subPayload = { sub: {password: ['******'], num: ['one', 'two']}}; - sendgrid.send(subPayload, function() { - expect(sendSpy.args[0][0].transmissionBody.substitutionData).to.deep.equal({ password: [ '******' ], num: [ 'one', 'two' ]}); - done(); - }); - }); - - it('should translate only sections into substitutionData appropriately', function(done) { - var sectionPayload = { section: {something: 'something else'}}; - sendgrid.send(sectionPayload, function() { - expect(sendSpy.args[0][0].transmissionBody.substitutionData).to.deep.equal({ something: 'something else'}); - done(); - }); - }); - - it('should not form substitutionData without substitutions or sections', function(done) { - var barePayload = {}; - sendgrid.send(barePayload, function() { - expect(sendSpy.args[0][0].transmissionBody.substitutionData).to.equal(undefined); - done(); - }); - }); - - it('should translate a full payload', function(done) { - sendgrid.send(payload, function() { - expect(sendSpy.args[0][0].transmissionBody).to.deep.equal(translatedPayload); - done(); - }); - }); - - it('should respond when the test succeeds', function(done) { - sendgrid.send({}, function(err, res) { - expect(res.body.ok).to.be.true; - expect(err).to.equal(null); - done(); - }); - }); - }); -}); diff --git a/test/spec/inboundDomains.spec.js b/test/spec/inboundDomains.spec.js index b80e111..ce4b3fe 100644 --- a/test/spec/inboundDomains.spec.js +++ b/test/spec/inboundDomains.spec.js @@ -1,105 +1,74 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Inbound Domains Library', function() { - var client, inboundDomains; + let client, inboundDomains; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - delete: sinon.stub().yields() - + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; inboundDomains = require('../../lib/inboundDomains')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - inboundDomains.all(function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri:'inbound-domains'}); - done(); - }); + describe('list Method', function() { + it('should call client get method with the appropriate uri', function() { + return inboundDomains.list() + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'inbound-domains'}); + }); }); }); - describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - inboundDomains.find('test', function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'inbound-domains/test'}); - done(); - }); - }); - - it('should throw an error if domain is null', function(done) { - inboundDomains.find(null, function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + describe('get Method', function() { + it('should call client get method with the appropriate uri', function() { + return inboundDomains.get('test') + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'inbound-domains/test'}); + }); }); - it('should throw an error if domain is missing', function(done) { - inboundDomains.find(function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(inboundDomains.get()).to.be.rejectedWith('domain is required'); }); }); describe('create Method', function() { - it('should call client post method with the appropriate uri', function(done) { - inboundDomains.create("test", function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('inbound-domains'); - done(); - }); + it('should call client post method with the appropriate uri and payload', function() { + let createOpts = {domain: 'test'}; + return inboundDomains.create(createOpts) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('inbound-domains'); + expect(client.post.firstCall.args[0].json).to.deep.equal(createOpts); + }); }); - it('should throw an error if domain is null', function(done) { - inboundDomains.create(null, function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if domain is missing', function(done) { - inboundDomains.create(function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(inboundDomains.create()).to.be.rejectedWith('create options are required'); }); }); describe('delete Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - inboundDomains.delete('test', function(err, data) { - expect(client.delete.firstCall.args[0].uri).to.equal('inbound-domains/test'); - done(); - }); - }); - - it('should throw an error if domain is null', function(done) { - inboundDomains.delete(null, function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should call client delete method with the appropriate uri', function() { + return inboundDomains.delete('test') + .then(function () { + expect(client.delete.firstCall.args[0].uri).to.equal('inbound-domains/test'); + }); }); - it('should throw an error if domain is missing', function(done) { - inboundDomains.delete(function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(inboundDomains.delete()).to.be.rejectedWith('domain is required'); }); }); }); diff --git a/test/spec/messageEvents.spec.js b/test/spec/messageEvents.spec.js index e26aee9..5b9fdfc 100644 --- a/test/spec/messageEvents.spec.js +++ b/test/spec/messageEvents.spec.js @@ -1,23 +1,28 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , Promise = require('../../lib/Promise'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Message Events Library', function() { - var client, templates; + let client, messageEvents; beforeEach(function() { client = { - get: sinon.stub().yields() + get: sinon.stub().resolves({}) }; messageEvents = require('../../lib/messageEvents')(client); }); describe('search Method', function() { - it('should call client get method with the appropriate parameters', function(done) { + it('should call client get method with the appropriate parameters', function() { var options = { bounce_classes: '10,50', campaign_ids: 'test_campaign', @@ -34,15 +39,15 @@ describe('Message Events Library', function() { to: '2016-11-14T16:15', transmission_ids: '65832150921904138' }; - messageEvents.search(options, function(err, data) { - Object.keys(options).forEach(function(key) { - expect(client.get.firstCall.args[0].qs).to.have.property(key).and.equal(options[key]); + return messageEvents.search(options) + .then(function() { + Object.keys(options).forEach(function(key) { + expect(client.get.firstCall.args[0].qs).to.have.property(key).and.equal(options[key]); + }); }); - done(); - }); }); - it('should accept arrays as parameters where appropriate', function(done) { + it('should accept arrays as parameters where appropriate', function() { var arroptions = { bounce_classes: [10,50], campaign_ids: ['campaign1', 'campaignTwo'], @@ -56,16 +61,16 @@ describe('Message Events Library', function() { per_page: 5, timezone: 'America/New_York' }; - messageEvents.search(arroptions, function(err, data) { - Object.keys(arroptions).forEach(function(key) { - var opt = arroptions[key] - , firstCallQS = client.get.firstCall.args[0].qs; - if (Array.isArray(opt)) { - expect(firstCallQS).to.have.property(key).and.equal(opt.toString()); - } + return messageEvents.search(arroptions) + .then(function() { + Object.keys(arroptions).forEach(function(key) { + var opt = arroptions[key] + , firstCallQS = client.get.firstCall.args[0].qs; + if (Array.isArray(opt)) { + expect(firstCallQS).to.have.property(key).and.equal(opt.toString()); + } + }); }); - done(); - }); }); }); }); diff --git a/test/spec/recipientLists.spec.js b/test/spec/recipientLists.spec.js index 670c2be..e0bee3f 100644 --- a/test/spec/recipientLists.spec.js +++ b/test/spec/recipientLists.spec.js @@ -1,174 +1,189 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Recipient Lists Library', function() { var client, recipientLists; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; recipientLists = require('../../lib/recipientLists')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - recipientLists.all(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists'); - done(); - }); + describe('list', function() { + + it('should call client get method with the appropriate uri', function() { + return recipientLists.list() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists'); + }); }); + }); - describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - recipientLists.find(options, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists/test'); - done(); - }); + describe('get', function() { + + it('should call client get method with the appropriate uri', function() { + return recipientLists.get('test-id') + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('recipient-lists/test-id'); + }); }); - it('should throw an error if id is missing', function(done) { - recipientLists.find(null, function(err) { - expect(err.message).to.equal('id is required'); - expect(client.get).not.to.have.been.called; - done(); + it('should throw an error if id is missing', function() { + return expect(recipientLists.get()).to.be.rejectedWith('id is required'); + }); + + it('should not throw an error if optional 2nd argument is a function (callback)', function() { + let cb = sinon.stub(); + return recipientLists.get('test-id', cb).then(() => { + expect(cb.callCount).to.equal(1); }); }); - it('should allow show_recipients to be set in options', function(done) { + it('should allow show_recipients to be set in options', function() { var options = { - id: 'test', show_recipients: true }; - recipientLists.find(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({show_recipients: true}); - done(); - }); + return recipientLists.get('test-id', options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({show_recipients: true}); + }); }); + }); - describe('create Method', function() { - var test_list = [ - { - address: { - email: 'test@test.com', - name: 'test' - } - } - ]; - - it('should call client post method with the appropriate uri', function(done) { - var options = { - recipients: test_list + describe('create', function() { + + it('should call client post method with the appropriate uri and payload', function() { + let testList = { + id: 'test_list', + recipients: [ + { + address: { + email: 'test@test.com', + name: 'test' + } + } + ] }; - recipientLists.create(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('recipient-lists'); - done(); - }); + return recipientLists.create(testList) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('recipient-lists'); + expect(client.post.firstCall.args[0].json).to.deep.equal(testList); + }); }); - it('should throw an error if id is missing', function(done) { - recipientLists.create(null, function(err) { - expect(err.message).to.equal('recipients list is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if no recipients are provided', function() { + return Promise.all([ + expect(recipientLists.create(), 'no recipient list hash at all').to.be.rejectedWith('recipient list is required'), + expect(recipientLists.create({}), 'no recipients key').to.be.rejectedWith('recipient list is required'), + expect(recipientLists.create(function() {}), 'recipient list is actually a callback').to.be.rejectedWith('recipient list is required') + ]); }); - it('should allow num_rcpt_errors to be set in options', function(done) { - var options = { - recipients: test_list, + it('should allow num_rcpt_errors to be set in options', function() { + var testList = { + id: 'test_list', + recipients: [ + { + address: { + email: 'test@test.com', + name: 'test' + } + } + ], num_rcpt_errors: 3 }; - recipientLists.create(options, function(err, data) { - expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); - done(); - }); + return recipientLists.create(testList) + .then(function() { + expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); + }); }); + }); - describe('update Method', function() { - var test_list = [ - { - address: { - email: 'test@test.com', - name: 'test' - } - } - ]; - - it('should call client put method with the appropriate uri', function(done) { - var options = { - id: 'test_list', - recipients: test_list + describe('update', function() { + + it('should call client put method with the appropriate uri and payload', function() { + const testList = { + recipients: [ + { + address: { + email: 'test@test.com', + name: 'test' + } + } + ] }; + const testId = 'test-id'; - recipientLists.update(options, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('recipient-lists/' + options.id); - done(); - }); + return recipientLists.update(testId, testList) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('recipient-lists/' + testId); + expect(client.put.firstCall.args[0].json).to.deep.equal(testList); + }); }); - it('should throw an error if id is missing', function(done) { - recipientLists.update(null, function(err) { - expect(err.message).to.equal('recipients list id is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if recipient list is missing', function() { + return expect(recipientLists.update('test-id')).to.be.rejectedWith('recipient list is required'); }); - it('should allow num_rcpt_errors to be set in options', function(done) { - var options = { - id: 'test_list', - recipients: test_list, + it('should throw an error if id is missing', function() { + return expect(recipientLists.update()).to.be.rejectedWith('recipient list id is required'); + }); + + it('should allow num_rcpt_errors to be set in options', function() { + var testList = { + recipients: [ + { + address: { + email: 'test@test.com', + name: 'test' + } + } + ], num_rcpt_errors: 3 }; - recipientLists.update(options, function(err, data) { - expect(client.put.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); - done(); - }); + return recipientLists.update('test-id', testList) + .then(function() { + expect(client.put.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); + }); }); }); - describe('delete Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - recipientLists.delete('test', function(err, data) { - expect(client['delete'].firstCall.args[0].uri).to.equal('recipient-lists/test'); - done(); - }); - }); + describe('delete', function() { - it('should throw an error if id is null', function(done) { - recipientLists['delete'](null, function(err) { - expect(err.message).to.equal('id is required'); - expect(client['delete']).not.to.have.been.called; - done(); - }); + it('should call client delete method with the appropriate uri', function() { + return recipientLists.delete('test') + .then(function() { + expect(client.delete.firstCall.args[0].uri).to.equal('recipient-lists/test'); + }); }); - it('should throw an error if id is missing', function(done) { - recipientLists['delete'](function(err) { - expect(err.message).to.equal('id is required'); - expect(client['delete']).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(recipientLists.delete()).to.be.rejectedWith('id is required'); }); + }); + }); diff --git a/test/spec/relayWebhooks.spec.js b/test/spec/relayWebhooks.spec.js index ea2991f..35aaa35 100644 --- a/test/spec/relayWebhooks.spec.js +++ b/test/spec/relayWebhooks.spec.js @@ -1,163 +1,101 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Relay Webhooks Library', function() { - var client, relayWebhooks; + let client, relayWebhooks; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - delete: sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; relayWebhooks = require('../../lib/relayWebhooks')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - relayWebhooks.all(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('relay-webhooks'); - done(); - }); + describe('list Method', function() { + it('should call client get method with the appropriate uri', function() { + return relayWebhooks.list() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('relay-webhooks'); + }); }); }); - describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - relayWebhooks.find('test', function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'relay-webhooks/test'}); - done(); - }); - }); - - it('should throw an error if relayWebhookId is null', function(done) { - relayWebhooks.find(null, function(err) { - expect(err.message).to.equal('relayWebhookId is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + describe('get Method', function() { + it('should call client get method with the appropriate uri', function() { + return relayWebhooks.get('test') + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'relay-webhooks/test'}); + }); }); - it('should throw an error if relayWebhookId is missing', function(done) { - relayWebhooks.find(function(err) { - expect(err.message).to.equal('relayWebhookId is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(relayWebhooks.get()).to.be.rejectedWith('id is required'); }); }); describe('create Method', function() { - it('should call client post method with the appropriate uri', function(done) { - var options = { + it('should call client post method with the appropriate uri and payload', function() { + let webhook = { target: 'test', domain: 'inbound.example.com' }; - relayWebhooks.create(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('relay-webhooks'); - done(); - }); - }); - - it('should throw an error if options is null', function(done) { - relayWebhooks.create(null, function(err) { - expect(err.message).to.equal('options are required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if options is missing', function(done) { - relayWebhooks.create(function(err) { - expect(err.message).to.equal('options are required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if target is missing from options', function(done) { - relayWebhooks.create({domain: 'inbound.example.com'}, function(err) { - expect(err.message).to.equal('target is required in options'); - expect(client.put).not.to.have.been.called; - done(); - }); + return relayWebhooks.create(webhook) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('relay-webhooks'); + expect(client.post.firstCall.args[0].json).to.deep.equal(webhook); + }); }); - it('should throw an error if domain is missing from options', function(done) { - relayWebhooks.create({target: 'test'}, function(err) { - expect(err.message).to.equal('domain is required in options'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if webhook object is missing', function() { + return expect(relayWebhooks.create()).to.be.rejectedWith('webhook object is required'); }); }); describe('update Method', function() { - it('should call client put method with the appropriate uri', function(done) { - var options = { - relayWebhookId: "test" + it('should call client put method with the appropriate uri and payload', function() { + let webhook = { + name: 'New Replies Webhook' }; - relayWebhooks.update(options, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('relay-webhooks/test'); - done(); - }); + return relayWebhooks.update('test', webhook) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('relay-webhooks/test'); + expect(client.put.firstCall.args[0].json).to.deep.equal(webhook); + }); }); - it('should throw an error if options is null', function(done) { - relayWebhooks.update(null, function(err) { - expect(err.message).to.equal('options are required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if webhook.id is missing', function() { + return expect(relayWebhooks.update()).to.be.rejectedWith('id is required'); }); - it('should throw an error if options is missing', function(done) { - relayWebhooks.update(function(err) { - expect(err.message).to.equal('options are required'); - expect(client.put).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if relayWebhookId is missing from options', function(done) { - relayWebhooks.update({}, function(err) { - expect(err.message).to.equal('relayWebhookId is required in options'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if webhook object is missing', function() { + return expect(relayWebhooks.update('test')).to.be.rejectedWith('webhook object is required'); }); }); describe('delete Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - relayWebhooks.delete('test', function(err, data) { - expect(client.delete.firstCall.args[0].uri).to.equal('relay-webhooks/test'); - done(); - }); - }); - - it('should throw an error if relayWebhookId is null', function(done) { - relayWebhooks.delete(null, function(err) { - expect(err.message).to.equal('relayWebhookId is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should call client delete method with the appropriate uri', function() { + return relayWebhooks.delete('test') + .then(function() { + expect(client.delete.firstCall.args[0].uri).to.equal('relay-webhooks/test'); + }); }); - it('should throw an error if relayWebhookId is missing', function(done) { - relayWebhooks.delete(function(err) { - expect(err.message).to.equal('relayWebhookId is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(relayWebhooks.delete()).to.be.rejectedWith('id is required'); }); }); }); diff --git a/test/spec/sendingDomains.spec.js b/test/spec/sendingDomains.spec.js index 512bc70..e8d3aa7 100644 --- a/test/spec/sendingDomains.spec.js +++ b/test/spec/sendingDomains.spec.js @@ -1,201 +1,124 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Sending Domains Library', function() { var client, sendingDomains; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - delete: sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; sendingDomains = require('../../lib/sendingDomains')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - sendingDomains.all(function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri:'sending-domains'}); - done(); - }); + describe('list', function() { + it('should call client get method with the appropriate uri', function() { + return sendingDomains.list() + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains'}); + }); }); }); - describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - sendingDomains.find('test', function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains/test'}); - done(); - }); + describe('get', function() { + it('should call client get method with the appropriate uri', function() { + return sendingDomains.get('test') + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'sending-domains/test'}); + }); }); - it('should throw an error if domain is null', function(done) { - sendingDomains.find(null, function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.get).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if domain is missing', function(done) { - sendingDomains.find(function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(sendingDomains.get()).to.be.rejectedWith('domain is required'); }); }); - describe('create Method', function() { - it('should call client post method with the appropriate uri', function(done) { - var domainBody = { - domain: "test" + describe('create', function() { + it('should call client post method with the appropriate uri and payload', function() { + var sendingDomain = { + domain: 'test' }; - sendingDomains.create(domainBody, function(err, data) { + return sendingDomains.create(sendingDomain).then(function() { expect(client.post.firstCall.args[0].uri).to.equal('sending-domains'); - done(); + expect(client.post.firstCall.args[0].json).to.deep.equal(sendingDomain); }); }); - it('should throw an error if domainBody is null', function(done) { - sendingDomains.create(null, function(err) { - expect(err.message).to.equal('domainBody is required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if domainBody is missing', function(done) { - sendingDomains.create(function(err) { - expect(err.message).to.equal('domainBody is required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if domain is missing from domainBody', function(done) { - sendingDomains.create({}, function(err){ - expect(err.message).to.equal('domain is required in the domainBody'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if create options are missing', function() { + return expect(sendingDomains.create()).to.be.rejectedWith('create options are required'); }); }); - describe('update Method', function() { - it('should call client put method with the appropriate uri', function(done) { - var domainBody = { - domain: "test" + describe('update', function() { + it('should call client put method with the appropriate uri and payload', function() { + var sendingDomain = { + tracking_domain: 'click.example1.com' }; - sendingDomains.update(domainBody, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('sending-domains/test'); - done(); - }); + return sendingDomains.update('test', sendingDomain) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('sending-domains/test'); + expect(client.put.firstCall.args[0].json).to.deep.equal(_.omit(sendingDomain, 'domain')); + }); }); - it('should throw an error if domainBody is null', function(done) { - sendingDomains.update(null, function(err) { - expect(err.message).to.equal('domainBody is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if update options are missing', function() { + return expect(sendingDomains.update('test')).to.be.rejectedWith('update options are required'); }); - it('should throw an error if domainBody is missing', function(done) { - sendingDomains.update(function(err) { - expect(err.message).to.equal('domainBody is required'); - expect(client.put).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if domain is missing from domainBody', function(done) { - sendingDomains.update({}, function(err){ - expect(err.message).to.equal('domain is required in the domainBody'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(sendingDomains.update()).to.be.rejectedWith('domain is required'); }); }); - describe('delete Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - sendingDomains.delete('test', function(err, data) { - expect(client.delete.firstCall.args[0].uri).to.equal('sending-domains/test'); - done(); - }); - }); - - it('should throw an error if domain is null', function(done) { - sendingDomains.delete(null, function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + describe('delete', function() { + it('should call client delete method with the appropriate uri', function() { + return sendingDomains.delete('test') + .then(function() { + expect(client.delete.firstCall.args[0].uri).to.equal('sending-domains/test'); + }); }); - it('should throw an error if domain is missing', function(done) { - sendingDomains.delete(function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(sendingDomains.delete()).to.be.rejectedWith('domain is required'); }); }); - describe('verify Method', function() { - it('should call client post method with the appropriate uri', function(done) { + describe('verify', function() { + it('should call client post method with the appropriate uri and payload', function() { var options = { - domain: 'test' + dkim_verify: true, + spf_verify: true }; - sendingDomains.verify(options, function() { - expect(client.post.firstCall.args[0].uri).to.equal('sending-domains/test/verify'); - done(); - }); - }); - - it('should throw an error if domain is missing', function(done) { - sendingDomains.verify(null, function(err) { - expect(err.message).to.equal('domain is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + return sendingDomains.verify('test', options) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('sending-domains/test/verify'); + expect(client.post.firstCall.args[0].json).to.deep.equal(_.omit(options, 'domain')); + }); }); - it('should default verifyDKIM and verifySPF to be true', function(done) { - var options = { - domain: 'test' - }; - - sendingDomains.verify(options, function() { - expect(client.post.firstCall.args[0].json.dkim_verify).to.be.true; - expect(client.post.firstCall.args[0].json.spf_verify).to.be.true; - done(); - }); + it('should throw an error if domain is missing', function() { + return expect(sendingDomains.verify()).to.be.rejectedWith('domain is required'); }); - it('should allow a user to set verifyDKIM and verifySPF', function(done){ - var options = { - domain: 'test', - verifyDKIM: false, - verifySPF: false - }; - - sendingDomains.verify(options, function() { - expect(client.post.firstCall.args[0].json.dkim_verify).to.be.false; - expect(client.post.firstCall.args[0].json.spf_verify).to.be.false; - done(); - }); + it('should throw an error if verification options are missing', function() { + return expect(sendingDomains.verify('test')).to.be.rejectedWith('verification options are required'); }); }); + }); diff --git a/test/spec/sparkpost.spec.js b/test/spec/sparkpost.spec.js index 700510f..12ed294 100644 --- a/test/spec/sparkpost.spec.js +++ b/test/spec/sparkpost.spec.js @@ -1,12 +1,13 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect , sinon = require('sinon') - , sinonChai = require('sinon-chai') , zlib = require('zlib') , nock = require('nock') , SparkPost = require('../../lib/sparkpost'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); describe('SparkPost Library', function() { @@ -65,6 +66,21 @@ describe('SparkPost Library', function() { expect(client.origin).to.equal('https://dev.sparkpost.com'); }); + it('should allow debug to be set in options', function() { + const key = '12345678901234567890'; + let options = {} + , client; + + // testing default initialization + client = new SparkPost(key, options); + expect(client.debug).to.equal(false); + + // testing setting flag + options.debug = true; + client = new SparkPost(key, options); + expect(client.debug).to.equal(true); + }); + describe('request method', function() { var client; @@ -94,11 +110,13 @@ describe('SparkPost Library', function() { var options = { method: 'GET' , uri: 'get/test' + , json: true + , debug: true }; client.request(options, function(err, data) { // making sure original request was GET - expect(data.request.method).to.equal('GET'); + expect(data.debug.request.method).to.equal('GET'); // finish async test done(); @@ -138,11 +156,8 @@ describe('SparkPost Library', function() { }; client.request(options, function(err, data) { - expect(data).to.be.defined; expect(err).to.be.defined; - expect(err.errors).to.deep.equal(data.body.errors); - // finish async test done(); }); @@ -178,10 +193,12 @@ describe('SparkPost Library', function() { var options = { method: 'GET' , uri: 'https://test.sparkpost.com/test' + , json: true + , debug: true }; client.request(options, function(err, data) { - expect(data.request.uri.href).to.equal('https://test.sparkpost.com/test'); + expect(data.debug.request.uri.href).to.equal('https://test.sparkpost.com/test'); // finish async test done(); @@ -196,9 +213,11 @@ describe('SparkPost Library', function() { method: 'GET' , uri: 'https://test.sparkpost.com/test' , gzip: true - }; + , json: true + , debug: true + }; - zlib.gzip(TEST_MESSAGE+TEST_MESSAGE, function(err, gzipped) { + zlib.gzip(JSON.stringify({ msg: TEST_MESSAGE+TEST_MESSAGE }), function(err, gzipped) { expect(err).to.be.null; compressedMsg = gzipped; gzipNock = nock('https://test.sparkpost.com', { @@ -214,8 +233,8 @@ describe('SparkPost Library', function() { }); client.request(options, function(err, data) { expect(err).to.be.null; - expect(data.statusCode).to.equal(200); - expect(data.body).to.equal(TEST_MESSAGE + TEST_MESSAGE); + expect(data.debug.statusCode).to.equal(200); + expect(data.msg).to.equal(TEST_MESSAGE + TEST_MESSAGE); // finish async test done(); @@ -228,19 +247,21 @@ describe('SparkPost Library', function() { nock('https://test.sparkpost.com') .get('/test') - .reply(200, TEST_MESSAGE); + .reply(200, { msg: TEST_MESSAGE }); var options = { method: 'GET' , uri: 'https://test.sparkpost.com/test' , gzip: false + , json: true + , debug: true }; client.request(options, function(err, data) { expect(err).to.be.null; - expect(data.statusCode).to.equal(200); - expect(data.body).to.equal(TEST_MESSAGE); - expect(data.headers).not.to.have.property('content-encoding'); + expect(data.debug.statusCode).to.equal(200); + expect(data.msg).to.equal(TEST_MESSAGE); + expect(data.debug.headers).not.to.have.property('content-encoding'); // finish async test done(); @@ -249,35 +270,68 @@ describe('SparkPost Library', function() { }); describe('get method', function() { - it('should deliver a GET + response', function(done) { - var requestSpy = sinon.spy(SparkPost.prototype, 'request'); + var client; + before(function() { + // setting up a client for all tests to use var key = '12345678901234567890'; - var client = new SparkPost(key); + var options = {}; + + client = new SparkPost(key, options); + }); + + it('should deliver a GET + response', function(done) { + var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') .get('/api/v1/get/test') .reply(200, { ok: true }); - client.get({uri: 'get/test'}, function(err, data) { + client.get({uri: 'get/test', debug: true}, function(err, data) { // need to make sure we called request method expect(requestSpy.calledOnce).to.be.true; // making sure original request was GET - expect(data.request.method).to.equal('GET'); + expect(data.debug.request.method).to.equal('GET'); SparkPost.prototype.request.restore(); // restoring function done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .get('/test') + .reply(200, '{ "ok": true }'); + + var options = { + uri: 'https://test.sparkpost.com/test' + }; + + client.get(options, function(err, data) { + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); + + // finish async test + done(); + }); + }); }); describe('post method', function() { - it('should deliver a POST', function(done) { - var requestSpy = sinon.spy(SparkPost.prototype, 'request'); + var client; + before(function() { + // setting up a client for all tests to use var key = '12345678901234567890'; - var client = new SparkPost(key); + var options = {}; + + client = new SparkPost(key, options); + }); + + it('should deliver a POST', function(done) { + var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') .post('/api/v1/post/test') @@ -288,6 +342,7 @@ describe('SparkPost Library', function() { , json: { testingData: 'test data' } + , debug: true }; client.post(reqOptions, function(err, data) { @@ -295,20 +350,49 @@ describe('SparkPost Library', function() { expect(requestSpy.calledOnce).to.be.true; // making sure original request was POST - expect(data.request.method).to.equal('POST'); + expect(data.debug.request.method).to.equal('POST'); SparkPost.prototype.request.restore(); // restoring function done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .post('/test') + .reply(200, '{ "ok": true }'); + + var options = { + uri: 'https://test.sparkpost.com/test' + , json: { + testingData: 'test data' + } + }; + + client.post(options, function(err, data) { + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); + + // finish async test + done(); + }); + }); }); describe('put method', function() { - it('should deliever a PUT/UPDATE', function(done) { - var requestSpy = sinon.spy(SparkPost.prototype, 'request'); + var client; + before(function() { + // setting up a client for all tests to use var key = '12345678901234567890'; - var client = new SparkPost(key); + var options = {}; + + client = new SparkPost(key, options); + }); + + it('should deliver a PUT/UPDATE', function(done) { + var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') .put('/api/v1/put/test') @@ -319,6 +403,7 @@ describe('SparkPost Library', function() { , json: { testingData: 'test data' } + , debug: true }; client.put(reqOptions, function(err, data) { @@ -326,20 +411,49 @@ describe('SparkPost Library', function() { expect(requestSpy.calledOnce).to.be.true; // making sure original request was PUT - expect(data.request.method).to.equal('PUT'); + expect(data.debug.request.method).to.equal('PUT'); SparkPost.prototype.request.restore(); // restoring function done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .put('/test') + .reply(200, '{ "ok": true }'); + + var options = { + uri: 'https://test.sparkpost.com/test' + , json: { + testingData: 'test data' + } + }; + + client.put(options, function(err, data) { + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); + + // finish async test + done(); + }); + }); }); describe('delete method', function() { - it('should deliever a DELETE', function(done) { - var requestSpy = sinon.spy(SparkPost.prototype, 'request'); + var client; + before(function() { + // setting up a client for all tests to use var key = '12345678901234567890'; - var client = new SparkPost(key); + var options = {}; + + client = new SparkPost(key, options); + }); + + it('should deliver a DELETE', function(done) { + var requestSpy = sinon.spy(SparkPost.prototype, 'request'); nock('https://api.sparkpost.com') .delete('/api/v1/delete/test') @@ -350,6 +464,7 @@ describe('SparkPost Library', function() { , json: { testingData: 'test data' } + , debug: true }; client.delete(reqOptions, function(err, data) { @@ -357,11 +472,33 @@ describe('SparkPost Library', function() { expect(requestSpy.calledOnce).to.be.true; // making sure original request was DELETE - expect(data.request.method).to.equal('DELETE'); + expect(data.debug.request.method).to.equal('DELETE'); SparkPost.prototype.request.restore(); // restoring function done(); }); }); + + it('should return a parsed JSON object', function(done) { + nock('https://test.sparkpost.com') + .delete('/test') + .reply(200, '{ "ok": true }'); + + var options = { + uri: 'https://test.sparkpost.com/test' + , json: { + testingData: 'test data' + } + }; + + client.delete(options, function(err, data) { + expect(data).to.not.be.a('string'); + expect(data).to.be.an('object'); + expect(data).to.deep.equal({ok: true}); + + // finish async test + done(); + }); + }); }); }); diff --git a/test/spec/subaccounts.spec.js b/test/spec/subaccounts.spec.js index d36d873..b4cec81 100644 --- a/test/spec/subaccounts.spec.js +++ b/test/spec/subaccounts.spec.js @@ -1,220 +1,90 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); -describe('Subaccounts Library', function () { - var client, subaccounts; +describe('Subaccounts Library', function() { + let client, subaccounts; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}) }; subaccounts = require('../../lib/subaccounts')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - subaccounts.all(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('subaccounts'); - done(); - }); + describe('list Method', function() { + it('should call client get method with the appropriate uri', function() { + return subaccounts.list() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('subaccounts'); + }); }); }); - describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var subaccountId = 'test'; - - subaccounts.find(subaccountId, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('subaccounts/test'); - done(); - }); + describe('get Method', function() { + it('should call client get method with the appropriate uri', function() { + return subaccounts.get('test') + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('subaccounts/test'); + }); }); - it('should throw an error if subaccountId is null', function(done) { - subaccounts.find(null, function(err) { - expect(err.message).to.equal('subaccountId is required'); - expect(client.get).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if subaccountId is missing', function(done) { - subaccounts.find(function(err) { - expect(err.message).to.equal('subaccountId is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(subaccounts.get()).to.be.rejectedWith('id is required'); }); }); describe('create Method', function() { - it('should call client post method with the appropriate uri', function(done) { - var options = { - name: 'test', - keyLabel: 'test', - keyGrants: [] - }; - - subaccounts.create(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('subaccounts'); - done(); - }); - }); - - it('should throw an error if options is null', function(done) { - subaccounts.create(null, function(err) { - expect(err.message).to.equal('options are required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if options is missing', function(done) { - subaccounts.create(function(err) { - expect(err.message).to.equal('options are required'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if name is missing from options', function(done) { - var options = { - keyLabel: 'test', - keyGrants: [] - }; - - subaccounts.create(options, function(err) { - expect(err.message).to.equal('name is required in options'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if keyLabel is missing from options', function(done) { - var options = { - name: 'test', - keyGrants: [] - }; - - subaccounts.create(options, function(err) { - expect(err.message).to.equal('keyLabel is required in options'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if keyGrants is missing from options', function(done) { - var options = { - name: 'test', - keyLabel: 'test' - }; - - subaccounts.create(options, function(err) { - expect(err.message).to.equal('keyGrants is required in options'); - expect(client.post).not.to.have.been.called; - done(); - }); - }); - - it('should not set key_valid_ips in request if keyValidIps is missing from options', function(done) { - var options = { - name: 'test', - keyLabel: 'test', - keyGrants: [] - }; - - subaccounts.create(options, function(err, data) { - expect(client.post.firstCall.args[0].json.key_valid_ips).to.be.undefined; - done(); - }) - }); - - it('should not set key_valid_ips in request if keyValidIps is empty array', function(done) { - var options = { + it('should call client post method with the appropriate uri and payload', function() { + var subaccount = { name: 'test', - keyLabel: 'test', - keyGrants: [], - keyValidIps: [] + key_label: 'test', + key_grants: [] }; - subaccounts.create(options, function(err, data) { - expect(client.post.firstCall.args[0].json.key_valid_ips).to.be.undefined; - done(); - }) + return subaccounts.create(subaccount) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('subaccounts'); + expect(client.post.firstCall.args[0].json).to.deep.equal(subaccount); + }); }); - it('should set key_valid_ips in request if keyValidIps is in options and is a non-empty array', function(done) { - var options = { - name: 'test', - keyLabel: 'test', - keyGrants: [], - keyValidIps: ['127.0.0.1'] - }; - - subaccounts.create(options, function(err, data) { - expect(client.post.firstCall.args[0].json.key_valid_ips).to.eql(['127.0.0.1']); - done(); - }) - }); - - it('should set key_valid_ips in request if keyValidIps is in options and is not an array', function(done) { - var options = { - name: 'test', - keyLabel: 'test', - keyGrants: [], - keyValidIps: '127.0.0.1' - }; - - subaccounts.create(options, function(err, data) { - expect(client.post.firstCall.args[0].json.key_valid_ips).to.eql(['127.0.0.1']); - done(); - }) + it('should throw an error if subaccount object is missing', function() { + return expect(subaccounts.create()).to.be.rejectedWith('subaccount object is required'); }); }); describe('update Method', function() { - it('should call client put method with the appropriate uri', function(done) { - var options = { - subaccountId: 'test' + it('should call client put method with the appropriate uri and payload', function() { + var subaccount = { + name: 'Hey Joe! Garage and Parts', + status: 'suspended', + ip_pool: '' }; - subaccounts.update(options, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('subaccounts/test'); - done(); - }); + return subaccounts.update('test', subaccount) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('subaccounts/test'); + expect(client.put.firstCall.args[0].json).to.deep.equal(subaccount); + }); }); - it('should throw an error if options is null', function(done) { - subaccounts.update(null, function(err) { - expect(err.message).to.equal('options are required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if subaccount id is missing from options', function() { + return expect(subaccounts.update()).to.be.rejectedWith('id is required'); }); - it('should throw an error if options is missing', function(done) { - subaccounts.update(function(err) { - expect(err.message).to.equal('options are required'); - expect(client.put).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if subaccountId is missing from options', function(done) { - var options = {}; - - subaccounts.update(options, function(err, data) { - expect(err.message).to.equal('subaccountId is required in options'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if subaccount object is missing', function() { + return expect(subaccounts.update('test')).to.be.rejectedWith('subaccount object is required'); }); }); }); diff --git a/test/spec/suppressionList.spec.js b/test/spec/suppressionList.spec.js index a661f11..f28be3b 100644 --- a/test/spec/suppressionList.spec.js +++ b/test/spec/suppressionList.spec.js @@ -1,119 +1,90 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Suppression List Library', function() { - var client, suppressionList; + let client, suppressionList; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; suppressionList = require('../../lib/suppressionList')(client); }); - describe('search Method', function() { - it('should call client get method with the appropriate uri', function(done) { - suppressionList.search({limit: 5}, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('suppression-list'); - done(); - }); + describe('list', function() { + it('should call client get method with the appropriate uri', function() { + return suppressionList.list({limit: 5}) + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('suppression-list'); + }); }); }); - describe('checkStatus Method', function() { - it('should call client get method with the appropriate uri', function(done) { - suppressionList.checkStatus('test@test.com', function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('suppression-list/test@test.com'); - done(); - }); + describe('get', function() { + it('should call client get method with the appropriate uri', function() { + return suppressionList.get('test@test.com') + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('suppression-list/test@test.com'); + }); }); - it('should throw an error if email is null', function(done) { - suppressionList.checkStatus(null, function(err) { - expect(err.message).to.equal('email is required'); - expect(client.get).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if email is missing', function(done) { - suppressionList.checkStatus(function(err) { - expect(err.message).to.equal('email is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if email is missing', function() { + return expect(suppressionList.get()).to.be.rejectedWith('email is required'); }); }); - describe('removeStatus Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - suppressionList.removeStatus('test@test.com', function(err, data) { - expect(client['delete'].firstCall.args[0].uri).to.equal('suppression-list/test@test.com'); - done(); - }); - }); - - it('should throw an error if email is null', function(done) { - suppressionList.removeStatus(null, function(err) { - expect(err.message).to.equal('email is required'); - expect(client['delete']).not.to.have.been.called; - done(); - }); - }); + describe('upsert', function() { + it('should accept a single list entry', function() { + var listEntry = { email: 'test@test.com' }; - it('should throw an error if email is missing', function(done) { - suppressionList.removeStatus(function(err) { - expect(err.message).to.equal('email is required'); - expect(client['delete']).not.to.have.been.called; - done(); - }); + return suppressionList.upsert(listEntry) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('suppression-list'); + expect(client.put.firstCall.args[0].json.recipients).to.deep.equal([listEntry]); + }); }); - }); - describe('upsert Method', function() { - it('should accept an array of recipients', function(done) { - var recipients = [ + it('should accept an array of list entries', function() { + var listEntries = [ { email: 'test1@test.com' }, { email: 'test2@test.com' } ]; - suppressionList.upsert(recipients, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('suppression-list'); - expect(client.put.firstCall.args[0].json.recipients).to.deep.equal(recipients); - done(); - }); + return suppressionList.upsert(listEntries) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('suppression-list'); + expect(client.put.firstCall.args[0].json.recipients).to.deep.equal(listEntries); + }); }); - it('should throw an error if recipient is null', function(done) { - suppressionList.upsert(null, function(err) { - expect(err.message).to.equal('recipient is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if recipient is missing', function() { + return expect(suppressionList.upsert()).to.be.rejectedWith('list entries is required'); }); + }); - it('should throw an error if recipient is missing', function(done) { - suppressionList.upsert(function(err) { - expect(err.message).to.equal('recipient is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + describe('delete', function() { + it('should call client delete method with the appropriate uri', function() { + return suppressionList.delete('test@test.com') + .then(function() { + expect(client.delete.firstCall.args[0].uri).to.equal('suppression-list/test@test.com'); + }); }); - it('should upsert a single recipient as an array', function(done) { - var recipient = { email: 'test1@test.com' }; - suppressionList.upsert(recipient, function(err, data) { - expect(client.put.firstCall.args[0].json.recipients).to.deep.equal([recipient]); - done(); - }); + it('should throw an error if email deleteEntry missing', function() { + return expect(suppressionList.delete()).to.be.rejectedWith('email is required'); }); }); + }); diff --git a/test/spec/templates.spec.js b/test/spec/templates.spec.js index 4043f2c..a0760bc 100644 --- a/test/spec/templates.spec.js +++ b/test/spec/templates.spec.js @@ -1,179 +1,183 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Templates Library', function() { var client, templates; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - 'delete': sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; templates = require('../../lib/templates')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - templates.all(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('templates'); - done(); - }); + describe('list Method', function() { + it('should call client get method with the appropriate uri', function() { + return templates.list() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('templates'); + }); }); }); - describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - templates.find(options, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('templates/test'); - done(); - }); + describe('get Method', function() { + it('should call client get method with the appropriate uri', function() { + var id = 'test'; + return templates.get(id) + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('templates/test'); + }); }); - it('should throw an error if id is missing', function(done) { - templates.find(null, function(err) { - expect(err.message).to.equal('template id is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(templates.get()).to.be.rejectedWith('template id is required'); }); - it('should allow draft to be set in options', function(done) { - var options = { - id: 'test', - draft: true - }; + it('should allow draft to be set in options', function() { + var id = 'test' + , options = { + draft: true + }; - templates.find(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({draft: true}); - done(); - }); + + return templates.get(id, options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({draft: true}); + }); }); }); describe('create Method', function() { - it('should call client post method with the appropriate uri', function(done) { - var options = { - template: { - id: "test" - } + it('should call client post method with the appropriate uri and payload', function() { + var template = { + id: 'test' }; - templates.create(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('templates'); - done(); - }); + return templates.create(template) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('templates'); + expect(client.post.firstCall.args[0].json).to.deep.equal(template); + }); }); - it('should throw an error if id is missing', function(done) { - templates.create(null, function(err) { - expect(err.message).to.equal('template object is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if template object is missing', function() { + return expect(templates.create()).to.be.rejectedWith('template object is required'); }); }); describe('update Method', function() { - it('should call client put method with the appropriate uri', function(done) { - var options = { - template: { - id: "test" - } - }; - - templates.update(options, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('templates/test'); - done(); - }); + it('should call client put method with the appropriate uri and payload', function() { + var id = 'test' + , template = { + name: 'A new name!' + }; + + return templates.update(id, template) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('templates/test'); + expect(client.put.firstCall.args[0].json).to.deep.equal(template); + }); }); - it('should throw an error if id is missing', function(done) { - templates.update(null, function(err) { - expect(err.message).to.equal('template object is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if template id is missing', function() { + return expect(templates.update()).to.be.rejectedWith('template id is required'); }); - it('should allow update_published to be set in options', function(done) { - var options = { - template: { - id: "test" - }, - update_published: true - }; + it('should throw an error if template object is missing', function() { + return expect(templates.update('test')).to.be.rejectedWith('template object is required'); + }); - templates.update(options, function(err, data) { - expect(client.put.firstCall.args[0].qs).to.deep.equal({update_published: true}); - done(); + it('should not throw an error if optional 3nd argument is a function (callback)', function() { + let cb = sinon.stub() + , id = 'test' + , template = { + name: 'A new name!' + }; + return templates.update(id, template, cb).then(function() { + expect(cb.callCount).to.equal(1); }); }); - }); - describe('delete Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - templates['delete']('test', function(err, data) { - expect(client['delete'].firstCall.args[0].uri).to.equal('templates/test'); - done(); - }); + it('should allow update_published to be set in options', function() { + var id = 'test' + , template = { + name: 'Test Template' + } + , options = { + update_published: true + }; + + return templates.update(id, template, options) + .then(function() { + expect(client.put.firstCall.args[0].qs).to.deep.equal(options); + }); }); + }); - it('should throw an error if id is null', function(done) { - templates['delete'](null, function(err) { - expect(err.message).to.equal('template id is required'); - expect(client['delete']).not.to.have.been.called; - done(); - }); + describe('delete Method', function() { + it('should call client delete method with the appropriate uri', function() { + return templates.delete('test') + .then(function() { + expect(client.delete.firstCall.args[0].uri).to.equal('templates/test'); + }); }); - it('should throw an error if id is missing', function(done) { - templates['delete'](function(err) { - expect(err.message).to.equal('template id is required'); - expect(client['delete']).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(templates.delete()).to.be.rejectedWith('template id is required'); }); }); describe('preview Method', function() { - it('should call client post method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - templates.preview(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('templates/test/preview'); - done(); - }); + it('should call client post method with the appropriate uri and payload', function() { + var id = 'test' + , options = { + substitution_data: { + 'name': 'Natalie', + 'age': 35, + 'member': true + } + }; + return templates.preview(id, options) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('templates/test/preview'); + expect(client.post.firstCall.args[0].json).to.deep.equal(options); + }); }); - it('should throw an error if id is missing', function(done) { - templates.preview(null, function(err) { - expect(err.message).to.equal('template id is required'); - expect(client.post).not.to.have.been.called; - done(); + it('should throw an error if id is missing', function() { + return expect(templates.preview()).to.be.rejectedWith('template id is required'); + }); + + it('should not throw an error if optional 2nd argument is a function (callback)', function() { + let cb = sinon.stub(); + return templates.preview('test', cb).then(function() { + expect(cb.callCount).to.equal(1); }); }); - it('should allow draft to be set in options', function(done) { - var options = { - id: 'test', - draft: true - }; + it('should allow draft to be set in options', function() { + var id = 'test' + , options = { + draft: true + }; - templates.preview(options, function(err, data) { - expect(client.post.firstCall.args[0].qs).to.deep.equal({draft: true}); - done(); - }); + return templates.preview(id, options) + .then(function() { + expect(client.post.firstCall.args[0].qs).to.deep.equal({draft: true}); + }); }); }); }); diff --git a/test/spec/toApiFormat.spec.js b/test/spec/toApiFormat.spec.js deleted file mode 100644 index 02aa250..0000000 --- a/test/spec/toApiFormat.spec.js +++ /dev/null @@ -1,184 +0,0 @@ -'use strict'; - -var chai = require('chai') - , sinon = require('sinon') - , sinonChai = require('sinon-chai') - , toApiFormat = require('../../lib/toApiFormat') - , expect = chai.expect - , _ = require('lodash') - ; - -chai.use(sinonChai); - -describe('toApiFormat', function() { - it('should recursively convert complex object keys to snake_case', function(done) { - var testObj = { - simpleString: "foo" - , boolVal: true - , numBers: 201 - , bangObj: { - strTwo: "bar" - , string_three: "skip" - } - , recipients: [ - {name: 'John Doe', address: 'j.doe@sparkpost.com'} - , {name: 'Sam Jones', address: 's.jones@sparkpost.com'} - ] - , content: { - email_rfc822: 'a message' - } - , fizzArr: [ - { - buzzInga: "buzz" - , bang: { - bellHop: "bell" - } - } - , { - bilBo: "baggins" - , alias: { - misTer: "underhill" - } - } - ] - , good_name: null - }; - - var validationObj = { - simple_string: "foo" - , bool_val: true - , num_bers: 201 - , bang_obj: { - str_two: "bar" - , string_three: "skip" - } - , recipients: [ - {name: 'John Doe', address: 'j.doe@sparkpost.com'} - , {name: 'Sam Jones', address: 's.jones@sparkpost.com'} - ] - , content: { - email_rfc822: 'a message' - } - , fizz_arr: [ - { - buzz_inga: "buzz" - , bang: { - bell_hop: "bell" - } - } - , { - bil_bo: "baggins" - , alias: { - mis_ter: "underhill" - } - } - ] - , good_name: null - }; - - var out = toApiFormat(testObj); - - expect(out).to.deep.equal(validationObj); - - done(); - }); - - it('should throw an error if it encounters one', function(done) { - var stub = sinon.stub(_, 'snakeCase').throws(); - - var testObj = { - simpleString: "foo" - , substitution_data: { - key1: 'value1', - key_2: 'value_2' - } - , sampleArray: [ - 'oneTag', - 'two_tag', - 'substitution_data', - 'tags' - ] - }; - - try { - var out = toApiFormat(testObj); - } catch(e) { - expect(e).to.not.be.null; - } - - stub.restore(); - done(); - }); - - it('should ignore sub-properties of properties on exclude list', function(done) { - var testObj = { - simpleString: "foo" - , substitution_data: { - key1: 'value1', - key_2: 'value_2' - } - , sampleArray: [ - { - goodValue: 'hello', - tags: [ - 'oneTag', - 'two_tag', - 'substitution_data', - 'tags' - ] - } - ] - }; - - var validationObj = { - simple_string: "foo" - , substitution_data: { - key1: 'value1', - key_2: 'value_2' - } - , sample_array: [ - { - good_value: 'hello', - tags: [ - 'oneTag', - 'two_tag', - 'substitution_data', - 'tags' - ] - } - ] - }; - - var out = toApiFormat(testObj); - - expect(out).to.deep.equal(validationObj); - - done(); - }); - - it('should preserve objects with number properties', function(done) { - var testObj = { - array: [ 0, 1, , , , 5, 6] - , object: { - "0": 0, - "1": 1, - "5": 5, - "6": 6 - } - , substitution_data: { - "0": 0, - "1": 1, - "5": 5, - "6": 6 - } - , tags: [ 0, 1, , , , 5, 6] - }; - - - var out = toApiFormat(_.clone(testObj)); - - expect(out).to.deep.equal(testObj); - - done(); - }); -}); diff --git a/test/spec/transmissions.spec.js b/test/spec/transmissions.spec.js index bbe50e3..08fc0f0 100644 --- a/test/spec/transmissions.spec.js +++ b/test/spec/transmissions.spec.js @@ -1,127 +1,129 @@ +'use strict'; + var chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Transmissions Library', function() { - var client, transmission; + var client, transmissions; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}) }; - transmission = require('../../lib/transmissions')(client); + transmissions = require('../../lib/transmissions')(client); }); describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - transmission.all(function() { + it('should call client get method with the appropriate uri', function() { + return transmissions.list() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('transmissions'); + }); + }); + + it('should call client get method with the appropriate uri using callback', function(done) { + transmissions.list(function() { expect(client.get.firstCall.args[0].uri).to.equal('transmissions'); done(); }); }); - it('should allow campaign_id to be set in options', function(done) { + it('should allow campaign_id to be set in options', function() { var options = { campaign_id: 'test-campaign' }; - transmission.all(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'}); - done(); - }); + return transmissions.list(options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({campaign_id: 'test-campaign'}); + }); }); - it('should allow template_id to be set in options', function(done) { + it('should allow template_id to be set in options', function() { var options = { template_id: 'test-template' }; - transmission.all(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'}); - done(); - }); + return transmissions.list(options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({template_id: 'test-template'}); + }); }); }); describe('find Method', function() { - it('should call client get method with the appropriate uri', function(done) { - transmission.find('test', function() { - expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'}); - done(); - }); + it('should call client get method with the appropriate uri', function() { + return transmissions.get('test') + .then(function() { + expect(client.get.firstCall.args[0]).to.deep.equal({uri: 'transmissions/test'}); + }); }); - it('should throw an error if transmissionID is null', function(done) { - transmission.find(null, function(err) { - expect(err.message).to.equal('transmissionID is required'); - expect(client.get).not.to.have.been.called; - done(); - }); - }); - - it('should throw an error if transmissionID is missing', function(done) { - transmission.find(function(err) { - expect(err.message).to.equal('transmissionID is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(transmissions.get()).to.be.rejectedWith('id is required'); }); }); describe('send Method', function() { - it('should call client post method with the appropriate uri', function(done) { - var options = { - transmissionBody: { - campaign: 'test-campaign' - } + it('should call client post method with the appropriate uri and payload', function() { + var transmission = { + campaign_id: 'test-campaign' }; - transmission.send(options, function() { - expect(client.post.firstCall.args[0].uri).to.equal('transmissions'); - done(); - }); + return transmissions.send(transmission) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('transmissions'); + expect(client.post.firstCall.args[0].json).to.deep.equal(transmission); + }); }); - it('should throw an error if transmissionBody is missing', function(done) { - transmission.send(null, function(err) { - expect(err.message).to.equal('transmissionBody is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if transmission object is missing', function() { + return expect(transmissions.send(function() {})).to.be.rejectedWith('transmission object is required'); }); - it('should allow num_rcpt_errors to be set in options', function(done) { - var options = { - transmissionBody: { - campaign: 'test-campaign' - }, - num_rcpt_errors: 3 - }; + it('should allow num_rcpt_errors to be set in options', function() { + var transmission = { + campaign_id: 'test-campaign' + } + , options = { + num_rcpt_errors: 3 + }; + + return transmissions.send(transmission, options) + .then(function() { + expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); + }); + }); - transmission.send(options, function(err, data) { - expect(client.post.firstCall.args[0].qs).to.deep.equal({num_rcpt_errors: 3}); - done(); + it('should not throw an error if optional 2nd argument is a function (callback)', function() { + let cb = sinon.stub() + , transmission = { + campaign_id: 'test-campaign' + }; + return transmissions.send(transmission, cb).then(function() { + expect(cb.callCount).to.equal(1); }); }); - it('should leave email_rfc822 content keys intact', function(done) { + it('should leave email_rfc822 content keys intact', function() { var options = { - transmissionBody: { - content: { - email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World' - } + content: { + email_rfc822: 'Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World' } }; - transmission.send(options, function(err, data) { - expect(client.post.firstCall.args[0].json.content).to.have.property('email_rfc822'); - done(); - }); + return transmissions.send(options) + .then(function() { + expect(client.post.firstCall.args[0].json.content).to.have.property('email_rfc822'); + }); }); }); }); diff --git a/test/spec/webhooks.spec.js b/test/spec/webhooks.spec.js index 1394d0f..2f79d49 100644 --- a/test/spec/webhooks.spec.js +++ b/test/spec/webhooks.spec.js @@ -1,267 +1,204 @@ -var chai = require('chai') +'use strict'; + +var _ = require('lodash') + , chai = require('chai') , expect = chai.expect - , sinon = require('sinon') - , sinonChai = require('sinon-chai'); + , sinon = require('sinon'); + +require('sinon-as-promised'); -chai.use(sinonChai); +chai.use(require('sinon-chai')); +chai.use(require('chai-as-promised')); describe('Webhooks Library', function() { var client, webhooks; beforeEach(function() { client = { - get: sinon.stub().yields(), - post: sinon.stub().yields(), - put: sinon.stub().yields(), - delete: sinon.stub().yields() + get: sinon.stub().resolves({}), + post: sinon.stub().resolves({}), + put: sinon.stub().resolves({}), + delete: sinon.stub().resolves({}) }; webhooks = require('../../lib/webhooks')(client); }); - describe('all Method', function() { - it('should call client get method with the appropriate uri', function(done) { - webhooks.all(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks'); - done(); - }); + describe('list Method', function() { + it('should call client get method with the appropriate uri', function() { + return webhooks.list() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('webhooks'); + }); }); - it('should allow timezone to be set in options', function(done) { + it('should allow timezone to be set in options', function() { var options = { timezone: 'America/New_York' }; - webhooks.all(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'}); - done(); - }); + return webhooks.list(options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'}); + }); }); }); - describe('describe Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - - webhooks.describe(options, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test'); - done(); - }); + describe('get Method', function() { + it('should call client get method with the appropriate uri', function() { + return webhooks.get('test') + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test'); + }); }); - it('should throw an error if id is missing', function(done) { - webhooks.describe(null, function(err) { - expect(err.message).to.equal('id is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(webhooks.get()).to.be.rejectedWith('id is required'); }); - it('should allow timezone to be set in options', function(done) { + it('should allow timezone to be set in options', function() { var options = { - id: 'test', timezone: 'America/New_York' }; - webhooks.describe(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'}); - done(); - }); + return webhooks.get('test', options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({timezone: 'America/New_York'}); + }); }); }); describe('create Method', function() { - it('should call client post method with the appropriate uri', function(done) { - webhooks.create({}, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('webhooks'); - done(); - }); - }); + it('should call client post method with the appropriate uri and payload', function() { + var webhook = { + name: 'Example webhook', + target: 'http://client.example.com/example-webhook', + events: ['delivery', 'injection', 'open', 'click'] + }; - it('should throw an error if webhook is null', function(done) { - webhooks.create(null, function(err) { - expect(err.message).to.equal('webhook object is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + return webhooks.create(webhook) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('webhooks'); + expect(client.post.firstCall.args[0].json).to.deep.equal(webhook); + }); }); - it('should throw an error if webhook is missing', function(done) { - webhooks.create(function(err) { - expect(err.message).to.equal('webhook object is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if webhook is missing', function() { + return expect(webhooks.create()).to.be.rejectedWith('webhook object is required'); }); }); describe('update Method', function() { - it('should call client put method with the appropriate uri', function(done) { + it('should call client put method with the appropriate uri', function() { var webhook = { - id: "test" + name: 'Renamed webhook', + events: ['rejection', 'delay'], + auth_type: 'none' }; - webhooks.update(webhook, function(err, data) { - expect(client.put.firstCall.args[0].uri).to.equal('webhooks/test'); - done(); - }); - }); - - it('should throw an error if webhook is null', function(done) { - webhooks.update(null, function(err) { - expect(err.message).to.equal('webhook object is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + return webhooks.update('test', webhook) + .then(function() { + expect(client.put.firstCall.args[0].uri).to.equal('webhooks/test'); + expect(client.put.firstCall.args[0].json).to.deep.equal(webhook); + }); }); - it('should throw an error if webhook is missing', function(done) { - webhooks.update(function(err) { - expect(err.message).to.equal('webhook object is required'); - expect(client.put).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(webhooks.update()).to.be.rejectedWith('id is required'); }); - it('should throw an error if webhook.id is missing', function(done) { - webhooks.update({}, function (err) { - expect(err.message).to.equal('webhook.id is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if webhook is missing', function() { + return expect(webhooks.update('test')).to.be.rejectedWith('webhook object is required'); }); }); describe('delete Method', function() { - it('should call client delete method with the appropriate uri', function(done) { - webhooks.delete('test', function(err, data) { - expect(client.delete.firstCall.args[0].uri).to.equal('webhooks/test'); - done(); - }); - }); - - it('should throw an error if id is null', function(done) { - webhooks.delete(null, function(err) { - expect(err.message).to.equal('id is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should call client delete method with the appropriate uri', function() { + return webhooks.delete('test') + .then(function() { + expect(client.delete.firstCall.args[0].uri).to.equal('webhooks/test'); + }); }); - it('should throw an error if id is missing', function(done) { - webhooks.delete(function(err) { - expect(err.message).to.equal('id is required'); - expect(client.delete).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(webhooks.delete()).to.be.rejectedWith('id is required'); }); }); describe('validate Method', function() { - it('should call client post method with the appropriate uri', function(done) { + it('should call client post method with the appropriate uri and payload', function() { var options = { - id: 'test', message: { msys: {} } }; - webhooks.validate(options, function(err, data) { - expect(client.post.firstCall.args[0].uri).to.equal('webhooks/test/validate'); - done(); - }); + return webhooks.validate('test', options) + .then(function() { + expect(client.post.firstCall.args[0].uri).to.equal('webhooks/test/validate'); + expect(client.post.firstCall.args[0].json).to.deep.equal(options); + }); }); - it('should throw an error if id is missing', function(done) { - webhooks.validate(null, function (err) { - expect(err.message).to.equal('id is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(webhooks.validate()).to.be.rejectedWith('id is required'); }); - it('should throw an error if message is missing', function(done) { - var options = { - id: 'test' - }; - - webhooks.validate(options, function (err) { - expect(err.message).to.equal('message is required'); - expect(client.post).not.to.have.been.called; - done(); - }); + it('should throw an error if message is missing', function() { + return expect(webhooks.validate('test')).to.be.rejectedWith('message is required'); }); }); describe('getBatchStatus Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - - webhooks.getBatchStatus(options, function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test/batch-status'); - done(); - }); + it('should call client get method with the appropriate uri', function() { + return webhooks.getBatchStatus('test') + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('webhooks/test/batch-status'); + }); }); - it('should throw an error if id is missing', function(done) { - webhooks.getBatchStatus(null, function (err) { - expect(err.message).to.equal('id is required'); - expect(client.get).not.to.have.been.called; - done(); - }); + it('should throw an error if id is missing', function() { + return expect(webhooks.getBatchStatus()).to.be.rejectedWith('id is required'); }); - it('should allow limit to be set in options', function(done) { + it('should allow limit to be set in options', function() { var options = { - id: 'test', limit: 1000 }; - webhooks.getBatchStatus(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({limit: 1000}); - done(); - }); + return webhooks.getBatchStatus('test', options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({limit: 1000}); + }); }); }); describe('getDocumentation Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - - webhooks.getDocumentation(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/documentation'); - done(); - }); + it('should call client get method with the appropriate uri', function() { + return webhooks.getDocumentation() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/documentation'); + }); }); }); describe('getSamples Method', function() { - it('should call client get method with the appropriate uri', function(done) { - var options = { - id: 'test' - }; - - webhooks.getSamples(function(err, data) { - expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/samples'); - done(); - }); + it('should call client get method with the appropriate uri', function() { + return webhooks.getSamples() + .then(function() { + expect(client.get.firstCall.args[0].uri).to.equal('webhooks/events/samples'); + }); }); - it('should allow events to be set in options', function(done) { + it('should allow events to be set in options', function() { var options = { events: 'bounces' }; - webhooks.getSamples(options, function(err, data) { - expect(client.get.firstCall.args[0].qs).to.deep.equal({events: 'bounces'}); - done(); - }); + return webhooks.getSamples(options) + .then(function() { + expect(client.get.firstCall.args[0].qs).to.deep.equal({events: 'bounces'}); + }); }); }); });