SparkPost Node.js Client

repository·master·Indexed 41 days ago

https://github.com/sparkpost/node-sparkpost

The official Node.js client library for SparkPost APIs (version 2.1.4). It provides a Promise-based interface for sending emails (transmissions), managing templates, subaccounts, inbound domains, and other resources. The library supports both Promises and error-first callbacks for asynchronous operations.

Tokens
15.9K
Snippets
65
Records
82
Agent score
51%

What's inside SparkPost

  1. Manage the Suppression List resource

    master

    The SparkPost Node.js client provides methods to manage your Suppression List, which contains email addresses that should not receive further communications.

    All methods in this library return Promises and also accept an optional callback as the last argument.

    Supported operations include:

    • list([parameters]): Retrieve entries filtered by search parameters.
    • get(email): Retrieve a specific entry by the recipient's email address.
    • upsert(listEntries): Insert or update one or many entries. Accepts a single entry object or an array of entry objects.
    • delete(email): Remove an entry by the recipient's email address.
  2. Use the SparkPost Base Object for unwrapped resources

    master

    The library may not wrap every SparkPost API resource (e.g., the Metrics resource). You can use the base object methods to perform requests to these unwrapped resources by providing a uri in the options object.

    All methods return Promises and accept an optional callback.

    // Example: Accessing the Metrics resource via the base object
    const options = {
      uri: 'metrics/domains'
    };
    
    client.get(options)
      .then(data => {
        console.log(data);
      })
      .catch(err => {
        console.log(err);
      });
  3. Declare and Initialize Variables

    master

    Follow these rules for variable management to avoid global scope pollution and hoisting issues:

    • Use var: Always use var to declare variables. Omitting it creates unintentional global variables.
    • Comma-First Style: When declaring multiple variables, use a single var declaration with comma-first formatting. Use line comments to group related variables.
    • Declaration Order: Declare unassigned variables last within their group.
    • Initialization: Initialize variables at declaration if the value is a primitive or a short single-line expression. If the initialization requires a multi-line expression, declare the variable first and assign it afterward.
    • Avoid Hoisting: Declare variables at the top of their scope to prevent unexpected behavior caused by JavaScript's hoisting mechanism.
    // Comma-first style with grouping
    var buffer = []
      , counter = 0
      , ref
    // Flags
      , canRotate = true
      , hasResults = false
      , isMutable = false;
    
    // Handling multi-line initialization
    var ref
      , len;
    ref = things[0]
        .map(function(item){ return item * 2; })
        .filter(function(item){ return (item % 2 === 0); });
    len = ref.length;
  4. Use Strings and Arrays correctly

    master

    Guidelines for handling primitive and complex data types:

    Strings

    • Use single-quoted strings exclusively.
    • For strings longer than 80 characters, use string concatenation across multiple lines.
    • Use Array.join() instead of concatenation when building strings programmatically.
    • Avoid building HTML strings; manipulate the DOM directly instead.

    Arrays

    • Use literal syntax ([]) for creation rather than new Array().
    • Use Array.push() to add elements to the end of an array.
    • Use Array.slice() to clone arrays.
    • Do not use associative arrays (e.g., arr['key'] = value). Use an Object or a Map instead.
    // Array best practices
    var items = [];
    
    var stack = [];
    stack.push('element');
    
    var src = [1, 2, 3];
    var dst = src.slice();
    
    // Use Objects for key-value pairs, not Arrays
    var items = {};
    items.animal = 'dog';
  5. Follow the SparkPost Node SDK Code Style Guide

    master

    This guide outlines the coding standards and conventions used within the SparkPost Node SDK. Adhering to these patterns ensures consistency, readability, and maintainability when contributing to or working with the codebase.

    Key areas covered include:

    • Comments: Using JSDoc for documentation and proper formatting for single/multiline comments.
    • Whitespace & Semicolons: Standardizing indentation (2-space soft tabs) and enforcing semicolon usage to avoid ASI (Automatic Semicolon Insertion) issues.
    • Blocks & Functions: Proper brace placement and function declaration patterns.
    • Conditions & Equality: Favoring explicit equality (===) and specific comparison patterns.
    • Library Usage: Guidelines on when to use native JavaScript versus external libraries like Lo-dash.
    • Composition: Avoiding deep method chaining in favor of temporary variables.
  6. Use Callbacks for async operations

    master

    If you prefer using callbacks, you can pass a callback function as the final argument to any library method. The library follows the standard Node.js error-first callback pattern: (err, data) => { ... }.

    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
    });
  7. Follow Naming Conventions for JavaScript

    master

    To maintain consistency with the SparkPost Node SDK, follow these naming rules:

    • Descriptive Names: Avoid single-letter names except in loops. Use query() instead of q().
    • camelCase: Use for objects, functions, and instances (e.g., myObject, myStringVariable).
    • PascalCase: Use for class names (e.g., SuperHero).
    • Private Properties: Do not use underscores (e.g., _property) to denote privacy. Instead, use closures in the constructor to keep properties private.
    • Context Reference: When referencing the current context, use self instead of that (assuming bind() is not used).
    // Good Naming Examples
    function query() { ... }
    
    for (var i = 0; i < 10; i++) { ... }
    
    var myObject = {};
    var myStringVariable = '';
    
    var SuperHero = function (options) {
      this.name = options.name;
    };
    var reed = new SuperHero({ name: 'Reed Richards' });
    
    function () {
      var self = this;
      return function () { console.log(self); };
    }
  8. Guidelines for reporting issues to SparkPost

    master

    Before submitting a new issue to the SparkPost repository, follow these steps to ensure it can be resolved efficiently:

    1. Search for existing issues: Check the existing issues list to prevent duplication.
    2. Provide a meaningful title: Give your issue a clear and descriptive name.
    3. Include required technical details:
      • Operating System and Version
      • Programming language version
      • Exception, error, or issue summary
      • Recreation steps or a Use case summary
      • Example data (if available)
      • Expected result or desired functionality
      • Any additional relevant information
    4. Maintain professional conduct: Avoid trolling or flaming comments.
    5. Monitor your issue: Follow or watch the issue to respond to contributor questions or requests for more information.
  9. Use Promises for async operations

    master

    All methods in the SparkPost Node.js client library return Promises by default. You can use .then() to handle successful API responses and .catch() to handle errors.

    let client = new SparkPost(key);
    
    client.templates.get(id)
      .then((data) => {
        // this the full API response body
      })
      .catch((err) => {
        // handle the sad error
      });
  10. Use Objects and Access Properties

    master

    Guidelines for working with objects:

    • Literal Syntax: Use {} for object creation rather than new Object().
    • Avoid Reserved Words: Do not use JavaScript reserved words as keys (e.g., class, default, private), even if quoted.
    • Property Access:
      • Use dot notation (obj.prop) when accessing properties by literal name.
      • Use bracket notation (obj[prop]) only when the property name is stored in a variable.
    • Prototype Modification: It is acceptable to modify native prototypes for compatibility (e.g., polyfilling Object.create), but do so conditionally to avoid breaking existing functionality.
    // Object best practices
    var obj = {};
    
    var Newton = {
      type: 'food',
      defaults: { flavor: 'strawberry' },
      hidden: true
    };
    
    // Property access
    var carrot = { category: 'plant', color: 'orange' };
    var color = carrot.color; // Use dot notation
    
    var propName = 'color';
    var colorVar = carrot[propName]; // Use bracket notation for variables
  11. Automatic payload formatting for transmissions

    master

    When using transmissions.send(), the library provides automatic payload formatting for recipient addresses and headers if the recipients field is an array.

    Address Formatting:

    • You can provide addresses as strings (e.g., "Name" <email@example.com> or just email@example.com).
    • The library converts these into the required object format: { name: '...', email: '...' }.

    CC and BCC Handling:

    • If you provide a cc or bcc array of recipients, the library will:
      1. Generate the appropriate CC header in content.headers.CC.
      2. Convert cc and bcc recipients into the standard recipients list.
      3. Automatically set the header_to property on CC/BCC recipients so they are excluded from the primary To header in the email metadata.