### Initialize SparkPost Client with API Key and Options Source: https://github.com/sparkpost/node-sparkpost/blob/master/README.md Examples demonstrating how to initialize the SparkPost client using an API key directly, from an environment variable, or with custom configuration options like a specific endpoint. This setup is crucial before making any API calls. ```JavaScript const SparkPost = require('sparkpost'); const client = new SparkPost('YOUR_API_KEY'); ``` ```JavaScript //Create an env var as SPARKPOST_API_KEY const SparkPost = require('sparkpost'); const client = new SparkPost(); ``` ```JavaScript const SparkPost = require('sparkpost'); const options = { endpoint: 'https://dev.sparkpost.com:443' }; const client = new SparkPost('YOUR_API_KEY', options); ``` -------------------------------- ### Avoid Manual Code Minification in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This example advises against manually minifying code by using short, non-descriptive variable names. It emphasizes that dedicated build tools should handle code minification to improve readability and maintainability. ```JavaScript // Bad var q = function q(s) { return document.querySelectorAll(s); }; var i,a=[],els=q('#test'); for(i=0;i'); // If you have a SparkPost EU account you will need to pass a different `origin` via the options parameter: // const euClient = new SparkPost('', { origin: 'https://api.eu.sparkpost.com:443' }); client.transmissions.send({ options: { sandbox: true }, content: { from: 'testing@sparkpostbox.com', subject: 'Hello, World!', html:'

Testing SparkPost - the world\'s most awesomest email service!

' }, recipients: [ {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); }); ``` -------------------------------- ### Initializing Variables at Declaration vs. Separate Assignment Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This example demonstrates best practices for variable initialization. It advises initializing variables directly at declaration if their value is immediately available and simple. For complex expressions spanning multiple lines, it recommends declaring the variable first and then assigning its value separately to maintain readability. ```JavaScript // Bad var ref , len; ref = things[0]; len = ref.length; // Good var ref = things[0] , len = ref.length; // Bad var ref = things[0] .map(function(item){ return item * 2; }) .filter(function(item){ return (item % 2 === 0); }) , len = ref.length; // Good var ref , len; ref = things[0] .map(function(item){ return item * 2; }) .filter(function(item){ return (item % 2 === 0); }); len = ref.length; ``` -------------------------------- ### JavaScript Multi-Clause Statement Style Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Illustrates the preferred style for multi-clause statements like `if/else` and `try/catch`, where subsequent clauses (`else`, `catch`) should start on the same line as the preceding closing brace. ```JavaScript // Bad if (test) { return thing.doThing(); } else { return undefined; } try { thing.doThing(); } catch (e) { console.log('Thing couldn\'t do thing: ' + e); } // Good if (test) { return thing.doThing(); } else { return undefined; } try { thing.doThing(); } catch (e) { console.log('Thing couldn\'t do thing: ' + e); } ``` -------------------------------- ### JavaScript Object Creation Using Literal Syntax Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Highlights the best practice of creating objects using the literal syntax (`{}`) in JavaScript, which is more concise and generally preferred over the `new Object()` constructor. ```javascript // Bad var obj = new Object(); // Good var obj = {}; ``` -------------------------------- ### JavaScript Block Style: Braces Placement Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates the correct placement of braces for multi-line blocks and function expressions in JavaScript, emphasizing that the opening brace should be on the same line as the statement or function declaration. ```JavaScript // Bad if (test) return false; // Good if (test) { return false; } // Bad var fn = function() { return false; }; // Good var fn = function() { return false; }; ``` -------------------------------- ### Use camelCase for Objects, Functions, and Instances in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This example demonstrates the correct camelCase convention for naming JavaScript variables, objects, and function instances. It contrasts this with incorrect naming styles such as PascalCase for instances, snake_case, and kebab-case. ```JavaScript // Bad var MYObject = {}; var my_string_variable = ''; var my-object-variable = {}; // Good var myObject = {}; var myStringVariable = ''; var myObjectVariable = {}; ``` -------------------------------- ### JavaScript Array Creation Using Literal Syntax Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Illustrates the recommended practice of using array literal syntax (`[]`) for creating new arrays in JavaScript, which is generally more concise and performant than the `new Array()` constructor. ```javascript // Bad var items = new Array(); // Good var items = []; ``` -------------------------------- ### Understanding JavaScript Hoisting with Functions Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This example clarifies the concept of hoisting in JavaScript, specifically differentiating between function declarations and function expressions. It demonstrates how function declarations are hoisted entirely, allowing them to be called before their definition, while function expressions (assigned to variables) only have their variable declaration hoisted, leading to a `TypeError` if called before assignment. The takeaway emphasizes declaring variables early to avoid such issues. ```JavaScript function test() { foo(); // TypeError "foo is not a function" bar(); // "This will run!" // Function expression assigned to local variable 'foo' var foo = function () { alert("This won't run!"); } // Function declaration, given the name 'bar' function bar() { alert("This will run!"); } } test(); ``` -------------------------------- ### Declaring Multiple Variables with Single `var` in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This example illustrates the recommended practice of declaring multiple variables using a single `var` statement. It advocates for the 'comma-first' style to enhance readability and suggests using line comments to logically group related variables, improving code organization and maintainability. ```JavaScript // Bad var buffer = []; var counter = 0; var ref; var canRotate = true; var hasResults = false; var isMutable = false; // Bad var buffer = [], counter = 0, ref, canRotate = true, hasResults = false, isMutable = false; // Good var buffer = [] , counter = 0 , ref // Flags , canRotate = true , hasResults = false , isMutable = false; ``` -------------------------------- ### Handle Private Properties with Closures in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This example explains how to achieve private properties in JavaScript using closures to encapsulate data, rather than relying on an underscore prefix (e.g., `_propertyName`), which is considered a bad practice for true privacy. ```JavaScript // Bad this._ccNumber = '4111111111111111'; // Good function AccountInfo(cardNumber) { var cardNumber = cardNumber; // initialization, &c. return this; } var acct = new AccountInfo('4111111111111111'); ``` -------------------------------- ### Documenting JavaScript Functions with JSDoc Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Illustrates how to effectively document JavaScript functions using JSDoc. It compares a basic comment with a more comprehensive JSDoc block, highlighting the benefits of JSDoc for providing detailed information about parameters, types, and return values, which improves code understanding and tooling support. ```JavaScript /* * Return an array whose (numeric) values are inverse of those in its argument. */ function invert(list) { return list.map(function(i) { return i - (2 * i); }); }; /** * Return an array whose (numeric) values are inverse of those in its argument. * @param {number[]} list - An array of numeric values. * @returns {number[]} An array of inverted values. */ function invert(list) { return list.map(function(i) { return i - (2 * i); }); }; ``` -------------------------------- ### JavaScript Conditional Evaluation Shortcuts Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates the use of truthiness/falsiness for concise conditional checks in JavaScript, replacing explicit empty string checks with simpler boolean evaluation. ```JavaScript // Bad if (name !== '') { // ... } // Good if (name) { // ... } ``` -------------------------------- ### JavaScript Indentation: Soft Tabs (2 Spaces) Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates the preferred use of soft tabs set to 2 spaces for indentation in JavaScript code. It contrasts this with incorrect indentation (e.g., 4 spaces), emphasizing that consistent 2-space indentation improves code readability and adheres to common JavaScript style guides. ```JavaScript var fn = () { ..console.log('test'); }; ``` -------------------------------- ### Use PascalCase for Class Names in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This snippet shows the proper use of PascalCase for naming constructor functions or classes in JavaScript. It highlights the distinction between class names and instance names, which should follow camelCase. ```JavaScript // Bad var superHero = function (options) { this.name = options.name; }; var reed = new superHero({ name:'Reed Richards' }); // Good var SuperHero = function (options) { this.name = options.name; }; var reed = new SuperHero({ name:'Reed Richards' }); ``` -------------------------------- ### JavaScript Brace Spacing Conventions Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Illustrates the rule of placing a single space before the leading brace in JavaScript function declarations and object literals. This consistent spacing convention enhances code readability and maintains a uniform style across the codebase. ```JavaScript var fn = () { console.log('test'); }; lookup.populate('Mr. Charles', { age: 32, job: JOB_SECURITY }); ``` -------------------------------- ### JavaScript Explicit Equality Checks and Constant Placement Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Explains the preference for strict equality (`===`, `!==`) over loose equality (`==`, `!=`) in JavaScript, and demonstrates the recommended practice of placing constants on the right-hand side of comparison operators. ```JavaScript // Bad: implicit "falsy" comparison if (! thing.doThing()) { // ... } // Bad: constant on left-hand side if (false === thing.doThing()) { // ... } // Good if (thing.doThing() === false) { // ... } ``` -------------------------------- ### Safely Extending Native JavaScript Object Prototypes Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Provides guidance on conditionally extending native JavaScript object prototypes. It demonstrates how to check if a method (like `Object.create`) already exists before defining it, preventing conflicts and ensuring compatibility across different JavaScript environments. ```javascript if (typeof Object.create == 'undefined') { Object.create = function (...) { // Implementation... } } ``` -------------------------------- ### JavaScript Function Parameter Naming: Avoid 'arguments' Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Illustrates why 'arguments' should not be used as a function parameter name in JavaScript to avoid shadowing the built-in `arguments` object, providing a correct alternative. ```JavaScript // Bad var fn = function nope(name, opts, arguments) { ... }; // Good var fn = function yep(name, opts, args) { ... }; ``` -------------------------------- ### Adding Elements to JavaScript Arrays with push() Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates the preferred method of adding elements to the end of an array using `Array.push()`, which is safer and more idiomatic than directly assigning to `stack[stack.length]`. ```javascript // Bad stack[stack.length] = 'element'; // Good stack.push('element'); ``` -------------------------------- ### SparkPost Client Request Methods API Reference Source: https://github.com/sparkpost/node-sparkpost/blob/master/README.md API documentation for the core request methods (`request`, `get`, `post`, `put`, `delete`) available on the SparkPost client. These methods handle HTTP requests to the SparkPost API and support both promise-based and callback-based asynchronous operations. ```APIDOC 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) options.debug: Setting to true includes full response from request client for debugging purposes. get | post | put | delete(options[, callback]) options: See request options Description: Request method will be overwritten and set to the same value as the name of these methods. ``` -------------------------------- ### Make Requests to Unwrapped Resources using Base Object Source: https://github.com/sparkpost/node-sparkpost/blob/master/README.md Example showing how to use the SparkPost client's base object to make requests to API resources not explicitly wrapped by the library, such as the Metrics API. This demonstrates flexibility for accessing any SparkPost API endpoint using the client's underlying request capabilities, handling responses with promises. ```JavaScript // 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); }); ``` -------------------------------- ### Improving Readability by Avoiding Excessive Method Chaining Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates how to improve code readability by breaking down long method chains into intermediate variables. This approach makes the flow of data transformations clearer and easier to debug compared to jQuery-style chaining. ```javascript // Bad anArray .map(function(item) { // ... }) .filter(function(item) { // ... }) ``` ```javascript // Good var mapping , result; mapping = anArray.map(function(item) { // ... }); result = mapping.filter(function(item) { // ... }); ``` -------------------------------- ### Preventing Unintentional Global Variables in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This snippet demonstrates the critical importance of using the `var` keyword when declaring variables in JavaScript. Failing to use `var` can lead to the creation of unintended global variables, which can cause unpredictable program behavior. The 'Good' example shows how `var` ensures variables remain scoped locally, preventing conflicts. ```JavaScript // Bad food = 'pickle'; ! function () { food = 'hot dogs'; }(); // food = 'hot dogs' // Good var food = 'pickle'; ! function () { var food = 'hot dogs'; }(); // food = 'pickle' ``` -------------------------------- ### JavaScript Multiline Comments: Bad vs. Good Practice Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates the preferred way to use multiline comments (`/* ... */`) in JavaScript for extensive blocks of text, contrasting it with using multiple single-line comments (`//`) which is considered less readable for such purposes. Emphasizes using the appropriate comment style for documentation clarity. ```JavaScript /* * No updates can be made to the resource during this operation as the * bookkeepping for it will NOT be performed because of possible race * conditions. All updates during this period will be ignored, so be * sure to reflect this in the UX. */ model.lock(); ``` -------------------------------- ### Preferring Native JavaScript Iteration Over Lodash Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Illustrates how to replace Lodash's `_.forEach` and `_.map` with native JavaScript array and object iteration methods. This practice promotes better modularity, reduces dependency on external libraries, and simplifies future maintenance. ```javascript var _ require('lodash') , anArray = [1, 2, 3, 4, 5] , anObject = {'foo': 1, 'bar': 2} , anotherObject; // No question of removing Lo-dash entirely: anotherObject = _.cloneDeep(anObject); // [...] // Bad: gratuitous use of Lo-dash _.forEach(anArray, function(val) { console.log(val); }); _.map(anObject, function(val, key) { console.log(key + ' = ' + val); }); ``` ```javascript anArray.forEach(function(val) { console.log(val); }); Object.keys(anObject).map(function(key) { var val = anObject[key]; console.log(key + ' = ' + val); }); ``` -------------------------------- ### APIDOC: Get Specific Sending Domain Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/sendingDomains.md Retrieves details for a specific sending domain by its name. This method returns a promise and optionally accepts a callback. ```APIDOC get(domain) domain: The domain name to look up (required) ``` -------------------------------- ### JavaScript Function Declaration in Non-Function Blocks Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Demonstrates the incorrect practice of declaring functions directly within non-function blocks (like `if` statements) and provides the correct approach of assigning a function to a variable instead. ```JavaScript // Bad if (enabled) { function test() { console.log('No'); } } // Good if (enabled) { var fn = function test() { console.log('Yes!'); }; } ``` -------------------------------- ### Avoid Single Letter Names in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This snippet illustrates the importance of using descriptive names for functions and variables in JavaScript, contrasting bad practices with good ones. Loop counters are an exception to this rule. ```JavaScript // Bad function q() {...} // Good function query() {...} for (var i = 0; i < 10; i++) { ... } ``` -------------------------------- ### Native JavaScript vs. Lodash for Basic Operations Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Compares using Lodash's `_.isEmpty` and `_.forEach` with native JavaScript methods (`.length`, `Object.keys().forEach`) for checking emptiness and iterating object keys. It recommends native methods for common, simple tasks to reduce external dependencies. ```javascript // Bad var _ = require('lodash') , items = [] , hasItems; hasItems = (_.isEmpty(thing.doThing()) === false); _.forEach(thing.things, function(value, key) { items.push(value); }); ``` ```javascript // Good var items = [] , hasItems; hasItems = (thing.doThing().length !== 0); Object.keys(thing.things).forEach(function(key) { var value = thing.things[key]; items.push(value); }); ``` -------------------------------- ### JavaScript Single-Line Comment Placement Guidelines Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Shows the recommended placement for single-line comments (`//`) in JavaScript. It advocates for placing them on a new line above the subject of the comment, typically with a blank line preceding it, to ensure clarity and proper separation, especially within complex control structures. ```JavaScript try { options = argsParser[parseType](argv); // Get the module to execute and its partner output module exe = options && require('./main-' + options.main); out = options && require('./output/main-' + options.main + '-output').create(sysUtil, options.debug, options.quiet); // Only execute with a proper pairing if (exe && out) { exe.exec(options, out, complete.bind(null, out, callback)) } } catch (ex) { // Create a generic/base 'out' module which can do the error printing out = Output.create(sysUtil, argv.indexOf('--debug') != -1) complete(out, callback, ex) } ``` -------------------------------- ### Cloning JavaScript Arrays Using slice() Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Explains how to correctly clone an array in JavaScript using `Array.slice()`. This prevents common issues like shallow copying (where `dst` still references `src`) and avoids inefficient manual iteration for copying elements. ```javascript // Bad var src = [1,2,3], dst = src; src[1] = 'string'; // dst = [1, 'string', 2] // Bad var src = [1,2,3], dst = []; for (var i, len = src.length; i < len; i++) { dst[i] = src[i]; } // Good var src = [1,2,3] , dst = src.slice(); ``` -------------------------------- ### Using JavaScript Objects for Associative Data Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Advises against using arrays for associative data (key-value pairs) in JavaScript, as this can lead to unexpected behavior with the `length` property. Instead, it recommends using plain objects (`{}`) for such purposes. ```javascript // Bad var items = []; items['animal'] = 'dog'; items['mineral'] = 'shale'; // items.length == 0 // Good var items = {}; items.animal = 'dog'; items.mineral = 'shale'; ``` -------------------------------- ### JavaScript Object Property Access: Dot vs. Bracket Notation Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Outlines the best practices for accessing object properties in JavaScript. It recommends using dot notation for direct literal property names and reserving bracket notation for cases where the property name is dynamic or stored in a variable. ```javascript var carrot = { category: 'plant', color: 'orange' } // Bad var color = carrot['color']; // Good var color = carrot.color; // Good var propName = 'color'; var color = carrot[propName]; // Good var carrot.getProp = function (prop) { return this[prop]; } ``` -------------------------------- ### Reference 'this' with 'self' in JavaScript Closures Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This snippet demonstrates the preferred convention of aliasing `this` to `self` when creating closures in JavaScript, especially when `bind()` is not used. This ensures the correct context of `this` is maintained within nested functions. ```JavaScript // Bad function () { var that = this; return function () { console.log(that); }; } // Good function () { var self = this; return function () { console.log(self); }; } ``` -------------------------------- ### JavaScript End-of-Line Comments for Variable Declarations Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Explains the appropriate use of end-of-line comments in JavaScript. This style is recommended only for documenting long lists of variable declarations or simple object properties, providing concise explanations right next to the declaration for improved readability without cluttering the code. ```JavaScript var lock = false, // Mandatory lock indicator , data = [] // Primary storage , buffer = [] // Used for swaps or copies , last = null // Points to last element of structure , current = null; // Used for iterators var struct = { lock: false, // Mandatory lock indicator data: [], // Primary storage buffer: [], // Used for swaps or copies last: null, // Points to last element of structure current: null // Used for iterators }; ``` -------------------------------- ### Avoiding JavaScript Reserved Words as Object Keys Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Warns against using JavaScript reserved words (like `class`, `default`, `private`) as object property names, even when quoted. This practice can lead to confusion, potential conflicts, and is generally considered bad style. ```javascript // Bad var Fig = { class: 'food', default: { flavor: 'strawberry' }, 'private': true }; // Good var Newton = { type: 'food', defaults: { flavor: 'strawberry' }, hidden: true }; ``` -------------------------------- ### Ordering Variable Declarations: Unassigned Last Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This snippet provides a guideline for ordering variable declarations, specifically recommending that unassigned variables be declared last within their respective groups. This practice contributes to clearer code by placing initialized variables first, followed by those awaiting assignment. ```JavaScript // Bad var ref, len, items = getItems(); // Good var items = getItems() , len , ref; ``` -------------------------------- ### JavaScript Semicolon Usage Best Practices Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md Discusses the importance of explicitly using semicolons in JavaScript to avoid issues related to Automatic Semicolon Insertion (ASI). It recommends always inserting semicolons where appropriate to prevent subtle bugs and ensure predictable code behavior, even though they are technically optional in some contexts. ```JavaScript (function () { var name = 'Ricky Bobby'; return name; })(); ``` -------------------------------- ### Declaring Variables at Top of Scope to Avoid Hoisting Issues Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/CODE_STYLE_GUIDE.md This snippet illustrates the best practice of declaring variables at the very beginning of their scope. This approach helps to prevent unexpected behavior that can arise from JavaScript's variable hoisting mechanism, where declarations are moved to the top of the scope during compilation, but assignments are not. ```JavaScript // Bad var InsertRecord = function (data) { validate(); notify.info('Inserting record'); var name = data.name; if (name === 'test') { return false; } else { return name; } }; // Good var InsertRecord = function (data) { var name = data.name; validate(); notify.info('Inserting record'); if (name === 'test') { return false; } else { return name; } }; ``` -------------------------------- ### SparkPost Client Constructor API Reference Source: https://github.com/sparkpost/node-sparkpost/blob/master/README.md Detailed API documentation for the `SparkPost` constructor, including required and optional parameters for initialization such as API key, endpoint, API version, and debugging options. It outlines how to configure the client instance. ```APIDOC new SparkPost(apiKey[, options]) apiKey: Required: yes (unless key is stored in SPARKPOST_API_KEY environment variable) Type: String Description: 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 Description: 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 Description: An optional identifier to include in the User-Agent header. e.g. product/1.0.0 options.headers: Required: no Type: Object Description: Set headers that apply to all requests. options.debug: Required: no Type: Boolean Default: false Description: 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. ``` -------------------------------- ### Run Project Tests Source: https://github.com/sparkpost/node-sparkpost/blob/master/CONTRIBUTING.md Instructions on how to execute the automated test suite for the SparkPost Node.js client library to ensure code quality and functionality before submitting a pull request. ```Shell npm test ``` -------------------------------- ### Publish Project to npm Registry Source: https://github.com/sparkpost/node-sparkpost/blob/master/CONTRIBUTING.md Command to publish the current version of the SparkPost Node.js client library to the npm registry. This step should be performed from the project root after a successful CI build and tag creation. ```Shell npm publish ``` -------------------------------- ### SparkPost Webhooks API Reference Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/webhooks.md Comprehensive API documentation for the SparkPost Webhooks resource, detailing all available methods, their parameters, and expected behaviors. All methods return promises and accept an optional callback. ```APIDOC Webhooks API: list([options]): Description: Lists all webhooks. Parameters: options.timezone: The timezone to use for the `last_successful` and `last_failure` properties. Default: `UTC`. get(id[, options]): Description: Get a single webhook by ID. Parameters: 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): Description: Create a new webhook. Parameters: webhook: A hash of webhook attributes. Required. update(id, webhook): Description: Update an existing webhook. Parameters: id: The id of the webhook to update. Required. webhook: A hash of webhook attributes. Required. delete(id): Description: Delete an existing webhook. Parameters: id: The id of the webhook to delete. Required. validate(id, options): Description: Sends an example message event batch from the Webhook API to the target URL. Parameters: id: The id of the webhook to validate. Required. options.message: The message (payload) to send to the webhook consumer. Required. getBatchStatus(id[, options]): Description: Gets recent status information about a webhook. Parameters: id: The id of the webhook. Required. options.limit: Maximum number of results to return. Default: `1000`. getDocumentation(): Description: Lists descriptions of the events, event types, and event fields that could be included in a webhooks post to your target URL. getSamples(options): Description: Lists examples of the event data that will be posted to a webhook consumer. Parameters: options.events: Event types for which to get a sample payload. Default: all event types returned. ``` -------------------------------- ### List All Webhooks using Node.js Client Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/webhooks.md Demonstrates how to list all webhooks using the SparkPost Node.js client library, handling both successful data retrieval and error cases with promises. ```JavaScript 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); }); ``` -------------------------------- ### SparkPost Templates API Methods Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/templates.md Overview of the available methods for interacting with the SparkPost Templates API, including parameters and their descriptions. All methods return promises and accept an optional last argument callback. ```APIDOC Templates Resource: list(): description: List a summary of all templates. get(id[, options]): description: Get details about a specified template by its id. parameters: id: string (required) description: The id of the template you want to look up. options.draft: boolean description: Specifies a draft or published template. create(template): description: Create a new template. parameters: template: object (required) description: An object of template attributes. update(id, template[, options]): description: Update an existing template. parameters: id: string (required) description: The id of the template you want to update. template: object (required) description: An object of template attributes. options.update_published: boolean description: If true, directly overwrite the existing published template. If false, create a new draft. delete(id): description: Delete an existing template. parameters: id: string (required) description: The id of the template you want to delete. preview(id[, options]): description: Preview the most recent version of an existing template by id. parameters: id: string (required) description: The id of the template you want to look up. options.substitution_data: object description: Object of substitution data. options.draft: boolean description: Specifies a draft or published template. ``` -------------------------------- ### SparkPost Node.js Client Supported API Resources Source: https://github.com/sparkpost/node-sparkpost/blob/master/README.md This section lists the various SparkPost API resources that are supported and accessible via the Node.js client library. Each entry indicates the API resource and its corresponding client property for interaction. ```APIDOC API Resources: - Inbound Domains: client.inboundDomains - Message Events: client.messageEvents - Events: client.events - Recipient Lists: client.recipientLists - Relay Webhooks: client.relayWebhooks - Sending Domains: client.sendingDomains - Subaccounts: client.subaccounts - Suppression List: client.suppressionList - Templates: client.templates - Transmissions: client.transmissions - Webhooks: client.webhooks ``` -------------------------------- ### SparkPost Relay Webhooks API Methods Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/relayWebhooks.md Defines the available methods for interacting with the SparkPost Relay Webhooks API, including their parameters and descriptions. All methods return promises and can accept an optional callback. ```APIDOC Relay Webhooks API Methods: list(): Description: List all relay webhooks. get(id: string): Description: Get details about a specified relay webhook by its id. Parameters: id: The id of the relay webhook you want to look up (required). create(webhook: object): Description: Create a new relay webhook. Parameters: webhook: An object of relay webhook attributes (required). update(id: string, webhook: object): Description: Update an existing relay webhook. Parameters: id: The id of the relay webhook you want to update (required). webhook: An object of relay webhook attributes (required). delete(id: string): Description: Delete an existing relay webhook. Parameters: id: The id of the relay webhook you want to delete (required). ``` -------------------------------- ### SparkPost Recipient Lists API Methods Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/recipientLists.md Defines the available methods for managing recipient lists via the SparkPost API, including their parameters, types, and descriptions. All methods return promises and optionally accept a callback. ```APIDOC RecipientListsAPI: __init__(): description: Provides methods for managing recipient lists. list(): description: List a summary of all recipient lists. get(id: string, options?: object): description: Retrieve details about a specified recipient list by its ID. parameters: id: The ID of the recipient list. (required) options.show_recipients: Specifies whether to retrieve the recipients. (Default: false) create(recipientList: object): description: Create a new recipient list. parameters: recipientList: An object of recipient list attributes. (required) recipientList.num_rcpt_errors: Limit the number of recipient errors returned. (Default: all errors returned) update(id: string, recipientList: object): description: Update an existing recipient list. parameters: id: The ID of the recipient list. (required) recipientList: An object of recipient list attributes. (required) recipientList.num_rcpt_errors: Limit the number of recipient errors returned. (Default: all errors returned) delete(id: string): description: Delete an existing recipient list. parameters: id: The ID of the recipient list you want to delete. (required) ``` -------------------------------- ### SparkPost Events API Reference Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/events.md This section details the available methods and parameter specifications for interacting with the SparkPost Events API. It covers the 'searchMessage' method and the required format for date/time parameters. ```APIDOC Events Resource: searchMessage([params, callback]) description: Search for events of type message. params: params: object (optional) description: A hash of Events URI Parameters. link: https://developers.sparkpost.com/api/events.html#events-get-search-for-message-events callback: function (optional) description: A callback function for handling the response. Date/Time Parameter Format: format: YYYY-MM-DDTHH:MM example: 2016-11-14T16:15 notes: Timestamps are expressed in the timezone specified by the 'timezone' parameter or UTC by default. ``` -------------------------------- ### SparkPost Transmissions API Methods Reference Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/transmissions.md Detailed reference for the SparkPost Transmissions API methods, including their purpose, parameters, and usage. This section outlines how to list, retrieve, and send transmissions. ```APIDOC Transmissions API: list(options[, callback]): Description: List an overview of all transmissions in the account Parameters: options.campaign_id: id of the campaign used by the transmission options.template_id: id of the template used by the transmission get(id[, callback]): Description: Retrieve the details about a transmission by its ID Parameters: id: id of the transmission you want to look up (required) send(transmission[, options, callback]): Description: Sends a message by creating a new transmission Parameters: transmission: an object of transmission attributes transmission.cc: Recipients to receive a carbon copy of the transmission transmission.bcc: Recipients to discreetly receive a carbon copy of the transmission options.num_rcpt_errors: maximum number of recipient errors returned ``` -------------------------------- ### SparkPost Subaccounts API Methods Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/subaccounts.md Documents the available methods for interacting with the SparkPost Subaccounts API, including listing all subaccounts, retrieving details for a specific subaccount by ID, creating a new subaccount with specified attributes, and updating an existing subaccount. ```APIDOC list([callback]) Description: List a summary of all subaccounts. get(id[, callback]) Description: Get details about a specified subaccount by its id. Parameters: id: The id of the subaccount you want to look up (required) create(subaccount[, callback]) Description: Create a new subaccount. Parameters: subaccount: An object of subaccount attributes (required) update(id, subaccount[, callback]) Description: Updates an existing subaccount. Parameters: id: The id of the subaccount you want to update (required) subaccount: An object of updatable subaccount attributes (required) ``` -------------------------------- ### SparkPost Inbound Domains API Methods Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/inboundDomains.md Defines the available methods for interacting with the SparkPost Inbound Domains API, including listing all domains, retrieving a specific domain, creating a new domain, and deleting an existing one. All methods return promises and optionally accept a callback. ```APIDOC InboundDomainsAPI: list(): description: List an overview of all inbound domains in the account. get(domain: string): description: Get an inbound domain by its domain name domain: The name of the domain you want to look up (required) create(createOpts: object): description: Create a new inbound domain createOpts: A hash of inbound domain attributes (required) delete(domain: string): description: Delete an existing inbound domain domain: The name of the domain you want to delete (required) ``` -------------------------------- ### Increment Project Version (Semantic Versioning) Source: https://github.com/sparkpost/node-sparkpost/blob/master/CONTRIBUTING.md Commands to update the project's version based on Semantic Versioning rules (patch, minor, major). These commands also handle committing version changes, tagging the release, and pushing to the upstream repository. ```Shell npm version patch ``` ```Shell npm version minor ``` ```Shell npm version major ``` -------------------------------- ### APIDOC: List Sending Domains Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/sendingDomains.md Retrieves an overview of all sending domains associated with the account. This method returns a promise and optionally accepts a callback. ```APIDOC list() ``` -------------------------------- ### SparkPost Message Events API Reference Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/messageEvents.md Detailed API documentation for interacting with SparkPost Message Events, including the primary search method and specifications for date/time parameters. ```APIDOC Methods: search([params, callback]) Description: Search for message events using the given parameters. Parameters: params: a hash of Message Events URI Parameters (https://developers.sparkpost.com/api/message-events.html#message-events-message-events-get) Notes: All methods return promises and accept an optional last argument callback. Read about how we handle callbacks and promises. Date/Time Parameter Format: Parameters: from, to Format: YYYY-MM-DDTHH:MM Example: 2016-11-14T16:15 Note: timestamps are expressed in the timezone specified by the timezone parameter or UTC by default. ``` -------------------------------- ### Handle SparkPost API Calls with Promises in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/async.md Demonstrates how to use Promises with the SparkPost Node.js client for asynchronous API calls. It shows how to chain `.then()` for successful responses to access the full API response body and `.catch()` for robust error handling. ```javascript let client = new SparkPost(key); client.templates.get(id) .then((data) => { // this the full API response body }) .catch((err) => { // handle the sad error }); ``` -------------------------------- ### APIDOC: Create New Sending Domain Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/sendingDomains.md Creates a new sending domain using the provided attributes. This method returns a promise and optionally accepts a callback. ```APIDOC create(createOpts) createOpts: A hash of sending domain attributes (required) ``` -------------------------------- ### SparkPost Node.js Suppression List API Methods Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/suppressionList.md Defines the available methods for interacting with the SparkPost Suppression List resource in the Node.js library. All methods return promises and accept an optional last argument callback. ```APIDOC SuppressionListResource: list(parameters?: object) description: List all entries in your suppression list, filtered by an optional set of search parameters. parameters: parameters: An object of search parameters (optional). get(email: string) description: Retrieve an entry by recipient email. parameters: email: The recipient email address (required). upsert(listEntries: object | Array) description: Insert or update one or many entries. parameters: listEntries: An object of entry list attributes or an array of entry list attribute objects. delete(email: string) description: Remove an entry by recipient email. parameters: email: The recipient email address to remove (required). ``` -------------------------------- ### APIDOC: Verify Sending Domain Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/sendingDomains.md Validates specified verification field types for a sending domain. This method returns a promise and optionally accepts a callback. ```APIDOC verify(domain, options) domain: The domain name to verify (required) options: A hash of verify attributes (required) ``` -------------------------------- ### Handle SparkPost API Calls with Callbacks in JavaScript Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/async.md Illustrates how to use error-first callbacks with the SparkPost Node.js client for asynchronous API calls. This approach involves passing a callback function as the last argument, which receives an error object (if any) and the response data, allowing for explicit error checking. ```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 }); ``` -------------------------------- ### APIDOC: Update Existing Sending Domain Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/sendingDomains.md Updates an existing sending domain identified by its name with the specified attributes. This method returns a promise and optionally accepts a callback. ```APIDOC update(domain, updateOpts) domain: The domain name to update (required) updateOpts: A hash of sending domain attributes (required) ``` -------------------------------- ### APIDOC: Delete Sending Domain Source: https://github.com/sparkpost/node-sparkpost/blob/master/docs/resources/sendingDomains.md Deletes an existing sending domain by its name. This method returns a promise and optionally accepts a callback. ```APIDOC delete(domain) domain: The domain name to delete (required) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.