npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

delighted

v2.1.0

Published

Delighted API Node Client

Downloads

50,653

Readme

Build Status

Delighted API Node Client

Official Node.js client for the Delighted API.

Note: This is intended for server-side use only and does not support client-side JavaScript.

Installation

Run npm install delighted --save to install.

Configuration

To get started, you need to require the client and configure it with your secret API key. You can require, configure and initialize the client in one go:

var delighted = require('delighted')('YOUR_API_KEY');

For further options, read the advanced configuration section.

Note: Your API key is secret, and you should treat it like a password. You can find your API key in your Delighted account, under Settings > API.

Usage

All resources can be accessed directly off of the delighted instance we created above. All actions immediately return a promise. In this initial example we'll create a person and log out their attributes when the promise resolves (finishes):

var params = {
  email: '[email protected]',
  name:  'Jony Appleseed',
  delay: 86400,
  properties: { plan: 'basic' } // an object to pass properties for segmentation
};

delighted.person.create(params).then(function(person) {
  console.log(person);
});

Previously subscribed people can be unsubscribed:

delighted.unsubscribe.create({ person_email: '[email protected]' });

Listing all people:

// List all people, auto pagination
// Note: this method automatically handles rate limits asynchronously
delighted.person
  .list()
  .autoPagingEach((person) => {
    // Do something with `person`
  })
  .then(() => {
    console.log('Done iterating.');
  }, (error) => {});

// If you wish to stop the pagination at any point, just return false
var count = 0;
delighted.person
  .list()
  .autoPagingEach((person) => {
    // Do something with `person`
    count++;
    if (count >= 2) {
      // Autopagination will stop after 2 interations
      return false;
    }
  })
  .then(() => {
    // After stopping, this will still get executed
    console.log('Done iterating.');
  }, (error) => {});

// You can limit the numbers of max successive retries during auto rate limits handling
delighted.person
  .list()
  .autoPagingEach((person) => {
      // Do something with `person`
    },
    { auto_handle_rate_limits_max_retries: 12 }
  )
  .then(() => {
    console.log('Done iterating.');
  }, (error) => {});


// You can also handle rate limits and other errors yourself
delighted.person
  .list()
  .autoPagingEach((person) => {
    // Do something with `person`
  }, { auto_handle_rate_limits: false })
  .then(() => {
    console.log('Done iterating.');
  }, (error) => {
    if (error.type == 'TooManyRequestsError') {
      // Indicates how long to wait (in seconds) before making this request again
      console.log(error.retryAfter);
    } else if (error.type == 'PaginationError') {
      // General pagination error
      console.log(error.message);
    }
  });

Get a paginated list of people who have unsubscribed:

delighted.unsubscribe.all({ page: 2}).then(function(responses) {
  responses.length; // => 20
});

Get a paginated list of people whose emails have bounced:

delighted.bounce.all({ page: 2}).then(function(responses) {
  responses.length; // => 20
});

Deleting a person and all of the data associated with them:

// Delete by person id
delighted.person.delete({ id: 42 })
// Delete by email address (must be E.164 format)
delighted.person.delete({ email: "[email protected]" })
// Delete by phone number
delighted.person.delete({ phone_number: "+14155551212" })

Pending survey requests can be deleted:

delighted.surveyRequest.deletePending({ person_email: '[email protected]' });

Responses can be created for somebody using their id. Note that the id is not the same as their email:

delighted.surveyResponse.create({ person: person.id, score: 10 });

Get a paginated list of all responses:

delighted.surveyResponse.all({ page: 2 }).then(function(responses) {
  responses.length; // => 20
});

Retrieve summary metrics of all responses:

delighted.metrics.retrieve();

Autopilot

Retrieve existing autopilot configuration for a platform:

delighted.autopilotConfiguration.retrieve('email');
delighted.autopilotConfiguration.retrieve('sms');

To interact with the autopilot person api, configure the autopilotMembership instance with the platform. You can list all people imported to Autopilot, add a new person, or delete an existing person:

// List all people in Autopilot
delighted.autopilotMembership.forEmail().list().autoPagingEach((person) => {
  console.log(person);
}, { auto_handle_rate_limits: true });
delighted.autopilotMembership.forSms().list().autoPagingEach((person) => {
  console.log(person);
}, { auto_handle_rate_limits: true });

// Create a new person
delighted.autopilotMembership.forEmail().create({ person_email: '[email protected]' });
delighted.autopilotMembership.forSms().create({ phone_number: '+15556667777' });

// Remove a person
delighted.autopilotMembership.forEmail().delete({ person_email: '[email protected]' });
delighted.autopilotMembership.forSms().delete( {phone_number: '+15556667777' });

Rate limits

If a request is rate limited, a DelightedError error is raised with a type of TooManyRequestsError. You can handle that error to implement exponential backoff or retry strategies. The error object provides a .retry_after property to tell you how many seconds you should wait before retrying. For example:

instance.metrics.retrieve().then(
  function(metrics) { ... },
  function(error) {
    if (error.type === 'TooManyRequestsError') { // rate limited
      var retryAfterSeconds = error.retryAfter;
      // wait for retryAfterSeconds before retrying
      // add your retry strategy here ...
    } else {
      // some other type of error
    }
  }
);

Advanced configuration & testing

All of the connection details can be configured through the delighted constructor, primarily for testing purposes. The available configuration options are:

  • host – defaults to api.delighted.com
  • port – defaults to 443
  • base – defaults to /v1
  • headers – defaults to specifying application/json for Accept and Content-Type and sets User-Agent to identify the Delighted API Node Client and version.
  • scheme – defaults to https

Testing with real requests against a mock server is the easiest way to integration test your application. For convenience, and our own testing, a test server is provided with the delighted package. Below is an example of testing the person resource within an application:

var delighted  = require('delighted');
var mockServer = require('delighted/server');
var instance   = delighted('DUMMY_API_KEY', {
  host:   'localhost',
  port:   5678,
  base:   '',
  scheme: 'http'
});

var mapping = {
  'POST /v1/people': {
    status: 201,
    body: { id: "1", email: '[email protected]', name: null, survey_scheduled_at: 1490298348 }
  }
};

var server = mockServer(5678, mapping);

Setting up the server only requires a port and a mapping. The mapping should match an exact endpoint and will send back a JSON body with the specified status code. With the server running you can then make a request:

instance.person.create({ email: '[email protected]' }).then(
  function(person) {
    console.log(person.survey_scheduled_at); //=> 1490298348
  },
  function(error) {
    console.log(error.type); //=> ResourceValidationError
  }
);

When you are done reading responses from the server, be sure to close it.

server.close();

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Run the tests (npm run-script test)
  4. Commit your changes (git commit -am 'Add some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create new Pull Request

Releasing

  1. Decide on the new version number (let's call it x).
  2. Update CHANGELOG.md with notes about the new version's changes.
  3. Update the version number in lib/Delighted.js and package.json and create a git tag for the version number (use git tag -l to check the format).
  4. Commit your changes to git and push the tag.
  5. Run npm publish --tag next to upload a pre-release to the NPM package registry, use npm publish --tag latest to upload the final release

Author

Originally by Sean McGary. Graciously transfered and now officially maintained by Delighted.