Giter Club home page Giter Club logo

node-sparkpost's Introduction

Sign up for a SparkPost account and visit our Developer Hub for even more content.

Node.js Client Library

Travis CI Coverage Status NPM version

The official Node.js binding for your favorite SparkPost APIs!

Prerequisites

Before using this library, you must have:

Installation

npm install sparkpost

Note: Node.js versions 0.10 and 0.12 are no longer supported.

Initialization

new SparkPost(apiKey[, options]) - Initialization

  • apiKey
    • Required: yes (unless key is stored in SPARKPOST_API_KEY environment variable)
    • Type: String
    • a passed in apiKey will take precedence over an environment variable
  • options.origin or options.endpoint
    • Required: no
    • Type: String
    • Default: https://api.sparkpost.com:443
      Note: To use the SparkPost EU API you will need to set this to https://api.eu.sparkpost.com:443.
  • options.apiVersion
    • Required: no
    • Type: String
    • Default: v1
  • options.stackIdentity
    • Required: no
    • Type: String
    • An optional identifier to include in the User-Agent header. e.g. product/1.0.0
  • options.headers
    • 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

Note: All methods return promises and accept an optional last argument callback. Read about how we handle callbacks and promises.

  • request(options[, callback])
    • options - see request modules options
    • options.uri - can either be a full url or a path that is appended to options.origin used at initialization (url.resolve)
    • options.debug - setting to true includes full response from request client for debugging purposes
  • get | post | put | delete(options[, callback])
    • options - see request options
    • Request method will be overwritten and set to the same value as the name of these methods.

Creating a SparkPost Client

Passing in an API key

const SparkPost = require('sparkpost');
const client = new SparkPost('YOUR_API_KEY');

Using an API key stored in an environment variable

//Create an env var as SPARKPOST_API_KEY
const SparkPost = require('sparkpost');
const client = new SparkPost();

Specifying non-default options

const SparkPost = require('sparkpost');
const options = {
  endpoint: 'https://dev.sparkpost.com:443'
};
const client = new SparkPost('YOUR_API_KEY', options);

Using the Node Client Library Base Object

We may not wrap every resource available in the SparkPost Client Library, for example the Node Client Library does not wrap the Metrics resource, but you can use the Node Client Library Base Object to form requests to these unwrapped resources. Here is an example request using the base object to make requests to the Metrics resource. Here is an example request using the base object to make requests to the Metrics resource.

// Get a list of domains that the Metrics API contains data on.
const options = {
  uri: 'metrics/domains'
};

client.get(options)
  .then(data => {
    console.log(data);
  })
  .catch(err => {
    console.log(err);
  });

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 instantiate, you can pass in an object with all the 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.

const SparkPost = require('sparkpost');
const client = new SparkPost('<YOUR API KEY>');

// If you have a SparkPost EU account you will need to pass a different `origin` via the options parameter:
// const euClient = new SparkPost('<YOUR API KEY>', { origin: 'https://api.eu.sparkpost.com:443' });

client.transmissions.send({
    options: {
      sandbox: true
    },
    content: {
      from: '[email protected]',
      subject: 'Hello, World!',
      html:'<html><body><p>Testing SparkPost - the world\'s most awesomest email service!</p></body></html>'
    },
    recipients: [
      {address: '<YOUR EMAIL ADDRESS>'}
    ]
  })
  .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);
  });

SparkPost API Resources Supported in Node Client Library

Click on the desired API to see usage and more information

Development

Setup

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 npm test

Contributing

Guidelines for adding issues

Our coding standards

Submitting pull requests

ChangeLog

See ChangeLog here

node-sparkpost's People

Contributors

aaron-em avatar aimeeknight avatar alexjpotter avatar artlogic avatar avigoldman avatar aydrian avatar bdeanindy avatar beardyman avatar bizob2828 avatar coldacid avatar colestrode avatar creatovisguru avatar danieljuhl avatar ewandennis avatar gpittarelli avatar jasonrhodes avatar jgzamora avatar jimlynchcodes avatar lfreneda avatar mary-grace avatar mstdokumaci avatar orval avatar richleland avatar rnzo avatar sstaley-sparkpost avatar teolag avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-sparkpost's Issues

Open Tracking & Click Tracking Options not Being Applied

Boolean logic in transmission.js toApiFormat() should change from:

 model.options.open_tracking = input.trackOpens || true;
 model.options.click_tracking = input.trackClicks || true;

to:

model.options.open_tracking = input.trackOpens === false ? false : true;
model.options.click_tracking = input.trackClicks === false ? false : true;

Add two new methods to Webhooks resource

  • List sample values and event descriptions - client.webhooks.events.getDocumentation(callback)
  • Selected payload of sample events - client.webhooks.events.getSamples(options, callback)

Issue for one of sample file

stored_template_send.js

This file does not have correct payload

Payload mentioned is

var trans = {
template: 'my-template',
from: 'From Envelope [email protected]',
subject: 'Example Email for Stored Template',
recipients: [{ address: { email: '[email protected]' } }]
};
error :
Example app listening at http://:::3000
{ [SparkPostError: Unprocessable Entity]
name: 'SparkPostError',
errors:
[ { message: 'required field is missing',
description: 'content object or template_id required',
code: '1400' } ],
statusCode: 422 }

The correct payload according to new api is ๐Ÿ‘

var trans = {

content: {
from: { 'name': 'jin', 'email': '[email protected]'},
subject: 'Your match results',
reply_to: '[email protected]',

    template_id :'test',

},

return_path: '[email protected]',
recipients: [{ address: { email: '[email protected]' } }]
};
or

var trans = {

content: {
from: { 'name': 'JIN', 'email': '[email protected]'},
subject: 'TESTING FROM SPARKPOST',
reply_to: '[email protected]',
html: '

IT WORKED!

',
text: 'IT WORKED'
},
return_path: '[email protected]',
recipients: [{ address: { email: '[email protected]' } }]
};

Update SuppressionList to use toApiFormat

Need to update the Suppression List resource to use the new toApiFormat module.

  • Include unit test changes as needed
  • Update to new module
  • Update examples once in stable working state

Update Transmissions SDK

Rename from transmission to transmissions for better API parity.
Add the missing querystring parameters.

useRecipientList sets list_name when it should be list_id

The useRecipientList method sets list_name. When submitted to the transmissions API it results in the following error:

{"message":"required field is missing","description":"recipients or list_id required","code":"1400"}

The list_name key needs to be updated to list_id.

Hide and default return_path

Sparkpost will not let users set the return_path, it will be set in policy instead. While the Transmission API requires this field currently, we need to just default it to "[email protected]" and remove ability for user to set it

Update Webhooks to use toApiFormat

Need to update the Webhook resource to use the new toApiFormat module.

  • Include unit test changes as needed
  • Update to new module
  • Update examples once in stable working state

Create a base resource object

When we shipped the sdk there was only one API. We had a pull request for sending-domains and a lot of duplicated code existed.

Task:
Build a base resource that takes care of all the common pieces like a fetch, create, building url

Add sandbox option to transmissions

The transmissions api has added a new option to the payload of a request; a sandbox option delineating whether or not a given transmission is using the sandbox domain or not.

The option itself is a boolean, and in the API payload, it's part of the options object (in with open/click tracking). The key the API accepts is sandbox

model.options.sandbox must be boolean

Unhandled check on request response

Naively checking a status code of an object and referencing another key without checking its parents

Patch below

diff --git a/lib/transmission.js b/lib/transmission.js
index befa640..e7e17e7 100644
--- a/lib/transmission.js
+++ b/lib/transmission.js
@@ -122,7 +122,7 @@ module.exports = {
     request.post(options, function(err, res, body) {
       if (err) {
         callback(err);
-      } else if (res.statusCode !== 200) {
+      } else if (res && res.body && res.statusCode !== 200) {
         callback(res.body.errors);
       } else {
         callback(null, body);

Follow better node.js conventions

The initial approach design was very java like.

  • Rip out all set methods
  • make the transmission return an object that has the functions(send, fetch, all)
  • no constructor
  • document the convention that camel case are translated to underscore based on keys names in transmission API

Clean up transmissions unit tests

We should clean up the unit tests for the Transmissions API. We should:

  • remove unnecessary tests, e.g., expect(method).to.be.a.function
  • mock dependencies
  • add tests for unhappy paths and boundary conditions

Update Sending Domains to use toApiFormat

Need to update SendingDomains to use the new toApiFormat module.

  • Include unit test changes as needed
  • Update to new module
  • Update examples once in stable working state

Valid API key parameter failing while creating new SparkPost(key) object && Update published NPM module

Valid API Key parameter failing while creating new SparkPost client object

The documentation says to supply a string, but the SDK is throwing an error unless you wrap the SparkPost String "key" parameter in an object and give it a single property name "key".

Example for workaround:

var SparkPost = require('sparkpost');
var spApiKeyObj = { key: '<yourSparkpostApiKeyHere>'};
var spEmailClient = new SparkPost(spApiKeyObj);

Example error code if you follow the documentation and examples (which only pass this in as an unwrapped string):

basicExpressApp/node_modules/sparkpost/lib/configuration.js:31
    throw new Error('You must provide an API key');
          ^
Error: You must provide an API key
    at Configuration.setConfig (basicExpressApp/node_modules/sparkpost/lib/configuration.js:31:11)
    at new module.exports (basicExpressApp/node_modules/sparkpost/index.js:8:10)
    at Object.<anonymous> (basicExpressApp/app.js:14:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Update published NPM module

Of course, looking deeper at this, I think there could be a mismatch between the published NPM module and the Github master branch source code. Here's why:

  • After running npm install --save sparkpost and setting up as defined above, the error is coming from: node_modules/sparkpost/lib/configuration.js:31:11
  • That file does not exist in the current SparkPost master branch code base

Provide export as .csv feature for GET responses

People may want to use the SDK to offer an easy "download as .csv" format for responses.

We should make that simple and bind it to the following SparkPost API services:

  • Templates
  • Recipient Lists
  • Suppression Lists
  • Sending Domains

Migrate docs to be in github wiki

Having our docs in README gets very cluttered. It would be good to create a github wiki and have pages for each resource within the SDK. Also perhaps a getting started/landing page

Accept camelCase or native API format seamlessly

We are currently using a toApiFormat method for each of the SDK's resources. This could be abstracted into a pseudo-static class of the SDK which can accept either format elegantly by mapping the request body to match the API standards for both camelCase and the SparkPost API's native format of delimiter separations with underscores "_".

Examples look to be out of date

Several of the examples reference the setRecipient method or setRecipients which don't actually exist on the Transmission prototype. They should be updated to be addRecipient and addRecipients.

Visual code coverage tool

It would be nice to view the code coverage visually instead of just the spec report at the end of unit tests. This would help find subtler issues like untested branches. We should set up something like coveralls.io. It's free for open source and plugs in nicely with Travis. We'll have to create an SparkPost account first. Other solutions would be fine too.

Support Promises

I was wondering if Sparkpost can support promises natively. Although there are libraries that can promisify functions, having native support would streamline the whole process.

Update Metrics to use toApiFormat

Need to update Metrics resource to use new toApiFormat module.

  • Include unit test changes as needed
  • Update to new module
  • Update examples once in stable working state

Update Transmissions List Example

Need to update the example for getting the collection using campaign_id and template_id filters as is described in the lib/transmissions.all().

Invalidate v1.0.0 through use of Express.js sample test harness

We want to make sure that everything works for the SDK both from a pure Node.js perspective as well as in Express.js (most common web server framework).

  • Test RecipientLists CRUD
  • Test Templates CRUD
  • Test SendingDomains CRUD
  • Test SuppressionList CRUD
  • Test Webhooks CRUD
  • Thoroughly test Transmissions for multiple cases:
    • Happy Path
    • Bad Request
    • 201, 204, and other 2xx level responses that are not "200"

Transmissions API Examples are out of date

the toApiFormat is flawed, the api requires that the template_id field live inside the content stanza of the post body to send a transmission, but the toApiFormat function does not construct the body in the way it is supposed. It will always result in a HTTP 422 from the API.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.