From bdc393b6f06bd7236b687b712e0f9c6ba963dfa5 Mon Sep 17 00:00:00 2001 From: Paul Proctor Date: Sat, 18 Apr 2020 11:42:48 -0400 Subject: [PATCH] Initial commit --- .eslintignore | 4 + .eslintrc.js | 40 + .gitignore | 8 + .travis.yml | 11 + LICENSE | 201 +++++ README.md | 222 ++++++ lib/deadmanssnitch_client.js | 758 +++++++++++++++++++ lib/index.js | 1 + lib/utils/errors.js | 98 +++ lib/utils/status.js | 65 ++ package.json | 54 ++ test/deadmanssnitch_client.test.js | 1093 ++++++++++++++++++++++++++++ test/helpers.js | 105 +++ test/tests.js | 2 + test/utils/errors.test.js | 203 ++++++ 15 files changed, 2865 insertions(+) create mode 100644 .eslintignore create mode 100644 .eslintrc.js create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 lib/deadmanssnitch_client.js create mode 100644 lib/index.js create mode 100644 lib/utils/errors.js create mode 100644 lib/utils/status.js create mode 100644 package.json create mode 100644 test/deadmanssnitch_client.test.js create mode 100644 test/helpers.js create mode 100644 test/tests.js create mode 100644 test/utils/errors.test.js diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..f528e46 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,4 @@ +test/**/*.js +.nyc_output/ +.vscode/ +coverage/ \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..92eb493 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,40 @@ +module.exports = { + env: { + commonjs: true, + es6: true, + node: true, + }, + extends: [ + 'google', + ], + globals: { + Atomics: 'readonly', + SharedArrayBuffer: 'readonly', + }, + parserOptions: { + ecmaVersion: 2018, + }, + rules: { + 'valid-jsdoc': [ 'error', { + requireParamDescription: false, + requireReturnDescription: false, + requireReturn: false, + prefer: { returns: 'returns' }, + }], + 'max-len': ['error', { + code: 85, + tabWidth: 2, + ignoreUrls: true, + }], + 'object-curly-spacing': [ 'error', 'always' ], + 'indent': [ + 'error', 2, { + 'CallExpression': { + 'arguments': 'off', + }, + } + ], + 'array-bracket-spacing': [ 'error', 'always' ], + 'no-console': 'error', + }, +}; diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9234a9f --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +node_modules +coverage/ +.nyc_output/ +.vscode/ +package-lock.json +yarn.lock +*.log +test/__*__.js \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..e98dce9 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - "8" + - "9" + - "10" + - "11" +script: + - npm run test:coverage +after_success: + - npm run test:coveralls + - npm run test:codecov \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..86e2bd2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 Paul Proctor + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..85fd860 --- /dev/null +++ b/README.md @@ -0,0 +1,222 @@ +# Dead Man's Snitch Client ![GitHub package.json version](https://img.shields.io/github/package-json/v/pauldenver/deadmanssnitch-client) [![Build Status](https://travis-ci.com/pauldenver/deadmanssnitch-client.svg?branch=master)](https://travis-ci.com/pauldenver/deadmanssnitch-client) [![Coverage Status](https://coveralls.io/repos/github/pauldenver/deadmanssnitch-client/badge.svg?branch=master)](https://coveralls.io/github/pauldenver/deadmanssnitch-client?branch=master) [![codecov](https://codecov.io/gh/pauldenver/deadmanssnitch-client/branch/master/graph/badge.svg)](https://codecov.io/gh/pauldenver/deadmanssnitch-client) + +The `deadmanssnitch-client` Node.js library contains a simple and convenient HTTP client for making requests to +Dead Man's Snitch check-ins and the [Dead Man's Snitch REST API](https://deadmanssnitch.com/docs/api/v1). + +## Table of contents + +- [Installation](#installation) +- [Usage](#usage) + - [Intialize the client](#initialize-the-client) + - [Importing](#example-import-methods) + - [Set environment variables in an application](#using-environment-variables-in-an-application) + - [Set environment variables on the command line](#setting-environment-variables-before-running-an-application) + - [Options](#options) +- [Examples](#examples) +- [Documentation](#documentation) +- [Change Log](#change-log) +- [License](#license) + +## Installation + +Using NPM: + +```bash +$ npm install deadmanssnitch-client +``` + +Using Yarn: + +```bash +$ yarn add deadmanssnitch-client +``` + +## Usage + +### Initializing a client + +The library exports a `DeadMansSnitchClient` class for interacting with Dead Man's Snitch check-ins and the +[Dead Man's Snitch REST API](https://deadmanssnitch.com/docs/api/v1). You'll need an API key provided by Dead Man's Snitch in order to interact with the Dead Man's Snitch REST API. An API key is required for REST API calls, but it is not necessary for snitch check-ins. You can provide the API key as an `apiKey` option or set the API key as an environment variable using `DMS_API_KEY`. By default, the client will use the `DMS_API_KEY` environment variable if the `apiKey` option is not provided. + +#### Example import methods: + +```javascript +const DeadMansSnitchClient = require('deadmanssnitch-client'); + +// Creating an API client. +const client = new DeadMansSnitchClient({ + apiKey: 'DEAD-MANS-SNITCH-API-KEY' +}); +``` + +```javascript +import DeadMansSnitchClient from 'deadmanssnitch-client'; + +// Creating an API client. +const client = new DeadMansSnitchClient({ + apiKey: 'DEAD-MANS-SNITCH-API-KEY' +}); +``` + +#### Using environment variables in an application: + +```javascript +const DeadMansSnitchClient = require('deadmanssnitch-client'); + +// Set the API key as an environment variable. +process.env.DMS_API_KEY = 'DEAD-MANS-SNITCH-API-KEY'; + +const client = new DeadMansSnitchClient(); +``` + +#### Setting environment variables before running an application: + +Linux: + +```bash +$ DMS_API_KEY=DEAD-MANS-SNITCH-API-KEY node app.js +``` + +Windows: + +```batch +> cmd /C "set DMS_API_KEY=DEAD-MANS-SNITCH-API-KEY && node app.js" +``` + +### Options + +These are the available options for creating a `DeadMansSnitchClient` instance. + +| Name | Default | Description | +| ------------------- | --------------------------------- | ----------------------------------------------------------- | +| `apiKey` | `undefined` | Dead Man's Snitch API Key | +| `timeout` | `5000` | Number of milliseconds before the request times out | +| `apiBaseUrl` | `https://api.deadmanssnitch.com` | Base URL for the Dead Man's Snitch REST API | +| `checkInBaseUrl` | `https://nosnch.in` | Base URL for the Dead Man's Snitch check-ins | +| `fullResponse` | `false` | Get the full response instead of just the body | +| `maxContentLength` | `10000` | The max size of the HTTP response content in bytes | +| `apiVersion` | `1` | The REST API Version to use | +
+ +## Examples + +The `checkIn` and REST API methods return a `Promise` which resolves with the response data or rejects with an error. + +Alternatively, the `checkIn` method and each of the REST API methods can also be provided a completion callback function as its last argument. When a callback function is used the corresponding method does not return a value. The arguments passed to the completion callback function are `err` and `resp`. The first argument (`err`) is always reserved for an exception/error and the second argument (`resp`) is always reserved for the data returned from the check-in or API call. If the corresponding method is completed successfully, then the first argument will be `undefined`. If the method fails, then the second argument will be `undefined`. + +Create an instance: + +```javascript +const DeadMansSnitchClient = require('deadmanssnitch-client'); + +// Creating an API client. +const client = new DeadMansSnitchClient({ + apiKey: 'DEAD-MANS-SNITCH-API-KEY' +}); +``` + +Check-in with a snitch: + +```javascript +async function performTask(token) { + /* + * Add task logic here. + */ + + // Check-in after a task completes. + await client.checkIn(token); +} +``` + +Check-in with a snitch and add a message: + +```javascript +async function performTask(token) { + /* + * Add task logic here. + */ + + // Check-in after a task completes. + await client.checkIn(token, `All's good man!`); +} +``` + +Get a list of snitches: + +```javascript +async function getAllSnitches() { + try { + return await client.getSnitches(); + } catch(err) { + console.error(err); + } +} +``` + +Get a certain snitch: + +```javascript +async function getSnitchInfo(token) { + try { + return await client.getSnitch(token); + } catch(err) { + console.error(err); + } +} +``` + +Create a new snitch: + +```javascript +async function createNewSnitch() { + try { + return await client.createSnitch({ + name: 'Web App', + interval: 'daily' + }); + } catch(err) { + console.error(err); + } +} +``` + +Update a snitch using a callback function: + +```javascript +async function updateMySnitch(token, snitchInfo) { + await client.updateSnitch(token, snitchInfo, (err, resp) => { + if (err) { + console.error(err); + } else { + console.log(resp); + } + }); +} +``` + +## Documentation + +- **`client.checkIn(token, message, callback)`** - Performs a check-in request for a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs) +- **`client.getSnitches(tags, callback)`** - Gets a list of snitches - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#listing-snitches) +- **`client.filterByStatus(status, callback)`** - Filters snitches by status - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#listing-snitches) +- **`client.filterByInterval(interval, callback)`** - Filters snitches by interval - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#listing-snitches) +- **`client.filterByAlertType(alertType, callback)`** - Filters snitches by alert type - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#listing-snitches) +- **`client.getSnitch(token, callback)`** - Get the information for a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#examining-a-snitch) +- **`client.createSnitch(snitchInfo, callback)`** - Creates a new snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#creating-a-snitch) +- **`client.updateSnitch(token, snitchInfo, callback)`** - Updates a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#updating-a-snitch) +- **`client.addTags(token, tags, callback)`** - Adds tags to a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#adding-tags) +- **`client.removeTag(token, tagName, callback)`** - Remove a tag from a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#removing-tags) +- **`client.changeTags(token, tags, callback)`** - Changes/replaces the tags of a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#changing-tags) +- **`client.removeAllTags(token, callback)`** - Removes all of the tags from a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#changing-tags) +- **`client.pauseSnitch(token, callback)`** - Pauses an active snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#pausing-a-snitch) +- **`client.deleteSnitch(token, callback)`** - Deletes a snitch - [Dead Man's Snitch Documentation](https://deadmanssnitch.com/docs/api/v1#deleting-a-snitch) + +## Change Log + +### v1.0.0 + +- Initial release + +## License + +This software is licensed under the [Apache 2 license](./LICENSE). \ No newline at end of file diff --git a/lib/deadmanssnitch_client.js b/lib/deadmanssnitch_client.js new file mode 100644 index 0000000..94c78f2 --- /dev/null +++ b/lib/deadmanssnitch_client.js @@ -0,0 +1,758 @@ +const axios = require('axios'); +const has = require('lodash.has'); +const isPlainObject = require('lodash.isplainobject'); +const isObjectLike = require('lodash.isobjectlike'); +const isEmpty = require('lodash.isempty'); + +// Import the error utils. +const { RequestError, StatusCodeError, + isAxiosRequestError, isAxiosResponseError } = require('./utils/errors'); +const httpStatus = require('./utils/status'); +const { version } = require('../package.json'); + +// Base URL for the Dead Man's Snitch API. +const API_BASE_URL = 'https://api.deadmanssnitch.com'; +// Base URL for the Dead Man's Snitch check-ins. +const CHECKIN_BASE_URL = 'https://nosnch.in'; +// Client user agent string. +const USER_AGENT = `DeadMansSnitch-Client/${version}`; +// Default API version. +const API_VERSION = 1; + +// Status values for snitches. +const SNITCH_STATUSES = [ + 'pending', + 'healthy', + 'failed', + 'errored', + 'paused', +]; + +// Interval values for snitches. +const SNITCH_INTERVALS = [ + '15_minute', + '30_minute', + 'hourly', + 'daily', + 'weekly', + 'monthly', +]; + +// Alert type values for snitches. +const SNITCH_ALERT_TYPES = [ 'basic', 'smart' ]; + +/** + * A library for interacting with Dead Man's Snitch check-ins + * and the Dead Man's Snitch REST API. + * + * @class DeadMansSnitchClient + */ +class DeadMansSnitchClient { + /** + * Creates an instance of DeadMansSnitchClient. + * + * @param {Object} [options={}] Client options. + * @memberof DeadMansSnitchClient + */ + constructor(options = {}) { + // Check the options. + if (!isPlainObject(options)) { + throw new TypeError('The client options must be an object'); + } + + this._options = options; + this._apiKey = this._getApiKey(this._options) || undefined; + + this.timeout = this._options.timeout || 5000; + this.apiBaseUrl = this._options.apiBaseUrl || API_BASE_URL; + this.checkInBaseUrl = this._options.checkInBaseUrl || CHECKIN_BASE_URL; + this.fullResponse = this._options.fullResponse || false; + this.maxContentLength = this._options.maxContentLength || 10000; + this.apiVersion = this._options.apiVersion || API_VERSION; + + // Create the Axios instances for the API and check-ins. + this._apiInstance = this._getAxiosInstance(this.apiBaseUrl); + this._checkInInstance = this._getAxiosInstance(this.checkInBaseUrl); + } + + /** + * Gets the Api Key from the provided options. + * + * @param {Object} options The client options. + * @returns {String} The Api Key. + * @memberof DeadMansSnitchClient + */ + _getApiKey(options) { + // Get the 'apiKey'. + if (has(options, 'apiKey') || has(process, 'env.DMS_API_KEY')) { + return (process.env.DMS_API_KEY || options.apiKey).trim(); + } + } + + /** + * Checks if the Api Key was set. + * + * @memberof DeadMansSnitchClient + */ + _checkApiKey() { + // Check the 'apiKey'. + if (!this._apiKey) { + throw new Error(`A Dead Man's Snitch Api Key is ` + + 'required for this action'); + } + } + + /** + * Gets the headers for a Dead Man's Snitch request. + * + * @param {String} baseURL The base URL for the request. + * @returns {Object} Request headers. + * @memberof DeadMansSnitchClient + */ + _getRequestHeaders(baseURL) { + // Get the headers for a check-in request. + if (baseURL === this.checkInBaseUrl) { + return { + 'Accept': 'text/plain; charset=utf-8', + 'Content-Type': 'text/plain; charset=utf-8', + 'User-Agent': USER_AGENT, + }; + } + + // Get the headers for an API request. + if (baseURL === this.apiBaseUrl && this._apiKey) { + return { + 'Accept': 'application/json; charset=utf-8', + 'Content-Type': 'application/json; charset=utf-8', + 'User-Agent': USER_AGENT, + }; + } + } + + /** + * Creates an Axios instance. + * + * @param {String} baseURL The base URL for the request. + * @returns {Axios} Axios instance. + * @memberof DeadMansSnitchClient + */ + _getAxiosInstance(baseURL) { + let auth; + // Get the headers. + const headers = this._getRequestHeaders(baseURL); + // Determine the response type. + const responseType = (baseURL === this.checkInBaseUrl) ? + 'document' : 'json'; + + if (baseURL === this.apiBaseUrl && this._apiKey) { + auth = { + username: this._apiKey, + password: '', + }; + } + + if (headers) { + return axios.create({ + baseURL, + headers, + responseType, + auth, + timeout: this.timeout, + responseEncoding: 'utf8', + maxContentLength: this.maxContentLength, + }); + } + } + + /** + * Gets the request options for a Healthchecks.io API request. + * + * @param {String} method HTTP method. + * @param {String} path HTTP request path. + * @param {Object} [qs=null] Query parameters. + * @param {Object|Array} [body=null] Request body. + * @returns {Object} Request options. + * @memberof DeadMansSnitchClient + */ + _getRequestOptions(method, path, qs = null, body = null) { + // Set the request options. + const options = { + method, + url: path, + params: (qs && isPlainObject(qs)) ? qs : undefined, + }; + + // Add body value (if needed). + if (/put|post|patch|delete/i.test(method) && + (body && (isPlainObject(body) || Array.isArray(body))) + ) { + options.data = body; + } + + return options; + } + + /** + * Performs a Dead Man's Snitch check-in or API request. + * + * @param {String} requestType The request to perform. + * @param {Object} options Request options. + * @returns {Promise} The response from the API request. + * @memberof DeadMansSnitchClient + */ + async _performRequest(requestType, options) { + let response; + + // Check the options. + if (!options || !isPlainObject(options) || isEmpty(options)) { + throw new Error('A request options object must be provided'); + } + + // Get the response. + if (requestType === 'check-in') { + response = await this._checkInInstance.request(options); + } else if (requestType === 'api') { + response = await this._apiInstance.request(options); + } else { + throw new Error('Received an unknown request type. Valid request types' + + ` are 'check-in' or 'api'`); + } + + // Should the full response be returned. + if (this.fullResponse) { + // Get the status message. + const statusMessage = response.statusText || httpStatus[response.status]; + + return { + statusCode: response.status, + statusMessage, + headers: response.headers, + data: response.data, + }; + } + + return response.data; + } + + /** + * Creates a custom error from an Axios error. + * + * @param {Error} err The 'axios' Error. + * @returns {Error} The custom error. + * @memberof DeadMansSnitchClient + */ + _handleError(err) { + // Check for Axios errors. + if (isAxiosRequestError(err)) { + return new RequestError(err); + } else if (isAxiosResponseError(err)) { + return new StatusCodeError(err); + } + + return err; + } + + /** + * Processes/executes the given callback function. + * + * @param {Error} err Error object. + * @param {String|Object|Array} resp Response data. + * @param {Function} callback Callback function. + * @returns {String|Object|Array} Response data. + * @memberof DeadMansSnitchClient + */ + _processCallback(err, resp, callback) { + if (callback) { + // Execute the callback. + callback(err, resp); + } else { + if (resp !== undefined && !err) { + return resp; + } else { + throw err; + } + } + } + + /** + * Performs a check-in request for a snitch. + * + * @param {String} token The snitch token. + * @param {String|Object|Array} message The snitch message. + * @param {Function} callback Callback function. + * @returns {Promise} The check-in response. + * @memberof DeadMansSnitchClient + */ + async checkIn(token, message, callback) { + const params = {}; + + // Determine if there is a message included. + if (message && isObjectLike(message)) { + // Turn any object or array into a string if provided. + params.m = JSON.stringify(message); + } else if (message && typeof message === 'string') { + params.m = message; + } + + try { + // Get the request options. + const options = this._getRequestOptions('GET', `/${token}`, params); + // Peform the request. + const resp = await this._performRequest('check-in', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Gets a list of snitches. + * + * @param {Array} [tags=[]] Filter tags. + * @param {Function} callback Callback function. + * @returns {Promise>} List of snitches. + * @memberof DeadMansSnitchClient + */ + async getSnitches(tags = [], callback) { + let params; + + // Check for the Api key. + this._checkApiKey(); + + // Get the tags. + if (tags && Array.isArray(tags)) { + if (tags.length > 0) { + const hasTags = tags.every((value) => { + return typeof value === 'string'; + }); + + if (hasTags) { + params = { + tags: (tags.length > 1) ? tags.join(',') : tags[0], + }; + } + } + } + + try { + // Get the request options. + const options = this._getRequestOptions('GET', + `/v${this.apiVersion}/snitches`, params); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Filters snitches by status. + * + * @param {String} status Snitch status value. + * @param {Function} callback Callback function. + * @returns {Promise>} List of filtered snitches. + * @memberof DeadMansSnitchClient + */ + async filterByStatus(status, callback) { + // Check for the Api key. + this._checkApiKey(); + + // Check the status value. + if (status && typeof status === 'string') { + if (!SNITCH_STATUSES.includes(status)) { + throw new Error('Received an invalid snitch status value'); + } + } else { + throw new Error(`The 'status' value must be a string`); + } + + try { + // Get the snitches. + const resp = await this.getSnitches(); + + // Filter by the status. + const snitches = resp.reduce((filtered, snitch) => { + // Check the status. + if (snitch.status === status) { + // Add the snitch. + filtered.push(snitch); + } + + return filtered; + }, []); + + // Process the callback. + return this._processCallback(undefined, snitches, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Filters snitches by interval. + * + * @param {String} interval Snitch interval value. + * @param {Function} callback Callback function. + * @returns {Promise>} List of filtered snitches. + * @memberof DeadMansSnitchClient + */ + async filterByInterval(interval, callback) { + // Check for the Api key. + this._checkApiKey(); + + // Check the interval value. + if (interval && typeof interval === 'string') { + if (!SNITCH_INTERVALS.includes(interval)) { + throw new Error('Received an invalid snitch interval value'); + } + } else { + throw new Error(`The 'interval' value must be a string`); + } + + try { + // Get the snitches. + const resp = await this.getSnitches(); + + // Filter by the interval. + const snitches = resp.reduce((filtered, snitch) => { + // Check the interval. + if (snitch.interval === interval) { + // Add the snitch. + filtered.push(snitch); + } + + return filtered; + }, []); + + // Process the callback. + return this._processCallback(undefined, snitches, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Filters snitches by alert type. + * + * @param {String} alertType Snitch alert type value. + * @param {Function} callback Callback function. + * @returns {Promise>} List of filtered snitches. + * @memberof DeadMansSnitchClient + */ + async filterByAlertType(alertType, callback) { + // Check for the Api key. + this._checkApiKey(); + + // Check the alert type value. + if (alertType && typeof alertType === 'string') { + if (!SNITCH_ALERT_TYPES.includes(alertType)) { + throw new Error('Received an invalid snitch alert type value'); + } + } else { + throw new Error(`The 'alertType' value must be a string`); + } + + try { + // Get the snitches. + const resp = await this.getSnitches(); + + // Filter by the alert type. + const snitches = resp.reduce((filtered, snitch) => { + // Check the alert type. + if (snitch.alert_type === alertType) { + // Add the snitch. + filtered.push(snitch); + } + + return filtered; + }, []); + + // Process the callback. + return this._processCallback(undefined, snitches, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Get the information for a snitch. + * + * @param {String} token The snitch token. + * @param {Function} callback Callback function. + * @returns {Promise} Snitch information. + * @memberof DeadMansSnitchClient + */ + async getSnitch(token, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('GET', + `/v${this.apiVersion}/snitches/${token}`); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Creates a new snitch. + * + * @param {Object} [snitchInfo={}] Snitch information. + * @param {Function} callback Callback function. + * @returns {Promise} Information for the snitch. + * @memberof DeadMansSnitchClient + */ + async createSnitch(snitchInfo = {}, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('POST', + `/v${this.apiVersion}/snitches`, null, snitchInfo); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Updates a snitch. + * + * @param {String} token The snitch token. + * @param {Object} [snitchInfo={}] Snitch information. + * @param {Function} callback Callback function. + * @returns {Promise} Snitch information. + * @memberof DeadMansSnitchClient + */ + async updateSnitch(token, snitchInfo = {}, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('PATCH', + `/v${this.apiVersion}/snitches/${token}`, null, snitchInfo); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Adds tags to a snitch. + * + * @param {String} token The snitch token. + * @param {Array} [tags=[]] Snitch tags. + * @param {Function} callback Callback function. + * @returns {Promise>} The current snitch tags. + * @memberof DeadMansSnitchClient + */ + async addTags(token, tags = [], callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('POST', + `/v${this.apiVersion}/snitches/${token}/tags`, + null, tags); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Remove a tag from a snitch. + * + * @param {String} token The snitch token. + * @param {String} tagName The tag to remove. + * @param {Function} callback Callback function. + * @returns {Promise>} The current snitch tags. + * @memberof DeadMansSnitchClient + */ + async removeTag(token, tagName, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('DELETE', + `/v${this.apiVersion}/snitches/${token}/tags/${tagName}`); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Changes/replaces the tags of a snitch. + * + * @param {String} token The snitch token. + * @param {Array} [tags=[]] Snitch tags. + * @param {Function} callback Callback function. + * @returns {Promise} Snitch information. + * @memberof DeadMansSnitchClient + */ + async changeTags(token, tags = [], callback) { + // Check for the Api key. + this._checkApiKey(); + + // Get the tags. + if (tags && Array.isArray(tags)) { + // Check the tag length. + if (tags.length === 0) { + throw new Error('At least one tag must be provided'); + } + } else { + throw new Error(`The 'tags' value must be an array with at least ` + + 'one string'); + } + + try { + // Update the snitch tags. + const resp = await this.updateSnitch(token, { tags }); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Removes all of the tags from a snitch. + * + * @param {String} token The snitch token. + * @param {Function} callback Callback function. + * @returns {Promise} Snitch information. + * @memberof DeadMansSnitchClient + */ + async removeAllTags(token, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Remove all of the snitch tags. + const resp = await this.updateSnitch(token, { tags: [] }); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Pauses an active snitch. + * + * @param {String} token The snitch token. + * @param {Function} callback Callback function. + * @returns {Promise} An empty string. + * @memberof DeadMansSnitchClient + */ + async pauseSnitch(token, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('POST', + `/v${this.apiVersion}/snitches/${token}/pause`); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } + + /** + * Deletes a snitch. + * + * @param {String} token The snitch token. + * @param {Function} callback Callback function. + * @returns {Promise} An empty string. + * @memberof DeadMansSnitchClient + */ + async deleteSnitch(token, callback) { + // Check for the Api key. + this._checkApiKey(); + + try { + // Get the request options. + const options = this._getRequestOptions('DELETE', + `/v${this.apiVersion}/snitches/${token}`); + // Peform the request. + const resp = await this._performRequest('api', options); + // Process the callback. + return this._processCallback(undefined, resp, callback); + } catch (err) { + // Get the custom error. + const error = this._handleError(err); + // Process the callback. + this._processCallback(error, undefined, callback); + } + } +} + +module.exports = DeadMansSnitchClient; diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..ccdf392 --- /dev/null +++ b/lib/index.js @@ -0,0 +1 @@ +module.exports = require('./deadmanssnitch_client'); diff --git a/lib/utils/errors.js b/lib/utils/errors.js new file mode 100644 index 0000000..18540f1 --- /dev/null +++ b/lib/utils/errors.js @@ -0,0 +1,98 @@ +const status = require('./status'); + +// Properties to remove from an Axios error. +const PROPS_TO_REMOVE = [ + 'config', + 'code', + 'request', + 'response', + 'isAxiosError', + 'toJSON', +]; + +// For removing certain values from an Axios error. +const stripAxiosError = (err) => { + // Remove the enhanced Error values. + PROPS_TO_REMOVE.forEach((value) => delete err[value]); + return err; +}; + +/** + * Error class for Axios request errors. + * + * @class RequestError + * @extends {Error} + */ +class RequestError extends Error { + /** + * Creates an instance of RequestError. + * + * @param {Error} cause Error object. + * @memberof RequestError + */ + constructor(cause) { + super(); + // Set the custom error values. + this.name = 'RequestError'; + this.message = String(cause); + this.cause = stripAxiosError(cause); + // Add the stack trace. + Error.captureStackTrace(this, RequestError); + } +} + +/** + * Error class for Axios status code (response) errors. + * + * @class StatusCodeError + * @extends {Error} + */ +class StatusCodeError extends Error { + /** + * Creates an instance of StatusCodeError. + * + * @param {Error} cause Error object. + * @memberof StatusCodeError + */ + constructor(cause) { + super(); + // Set the custom error values. + this.name = 'StatusCodeError'; + this.message = String(cause); + this.statusCode = cause.response.status; + this.statusMessage = cause.response.statusText || + status[`${this.statusCode}`]; + this.headers = cause.response.headers; + this.body = cause.response.data; + this.cause = stripAxiosError(cause); + // Add the stack trace. + Error.captureStackTrace(this, StatusCodeError); + } +} + +/** + * Determines if an error is an 'axios' request error. + * + * @param {Error} err The 'axios' Error. + * @returns {Boolean} Request error or not. + */ +function isAxiosRequestError(err) { + return err && err.config && err.response === undefined; +} + +/** + * Determines if an error is an 'axios' response error. + * + * @param {Error} err The 'axios' Error. + * @returns {Boolean} Response error or not. + */ +function isAxiosResponseError(err) { + return err && err.response && err.response.status !== undefined; +} + +module.exports = { + RequestError, + StatusCodeError, + isAxiosRequestError, + isAxiosResponseError, +}; diff --git a/lib/utils/status.js b/lib/utils/status.js new file mode 100644 index 0000000..07237cd --- /dev/null +++ b/lib/utils/status.js @@ -0,0 +1,65 @@ +module.exports = { + '100': 'Continue', + '101': 'Switching Protocols', + '102': 'Processing', + '103': 'Early Hints', + '200': 'OK', + '201': 'Created', + '202': 'Accepted', + '203': 'Non-Authoritative Information', + '204': 'No Content', + '205': 'Reset Content', + '206': 'Partial Content', + '207': 'Multi-Status', + '208': 'Already Reported', + '226': 'IM Used', + '300': 'Multiple Choices', + '301': 'Moved Permanently', + '302': 'Found', + '303': 'See Other', + '304': 'Not Modified', + '305': 'Use Proxy', + '307': 'Temporary Redirect', + '308': 'Permanent Redirect', + '400': 'Bad Request', + '401': 'Unauthorized', + '402': 'Payment Required', + '403': 'Forbidden', + '404': 'Not Found', + '405': 'Method Not Allowed', + '406': 'Not Acceptable', + '407': 'Proxy Authentication Required', + '408': 'Request Timeout', + '409': 'Conflict', + '410': 'Gone', + '411': 'Length Required', + '412': 'Precondition Failed', + '413': 'Payload Too Large', + '414': 'URI Too Long', + '415': 'Unsupported Media Type', + '416': 'Range Not Satisfiable', + '417': 'Expectation Failed', + '418': `I'm a teapot`, + '421': 'Misdirected Request', + '422': 'Unprocessable Entity', + '423': 'Locked', + '424': 'Failed Dependency', + '425': 'Unordered Collection', + '426': 'Upgrade Required', + '428': 'Precondition Required', + '429': 'Too Many Requests', + '431': 'Request Header Fields Too Large', + '451': 'Unavailable For Legal Reasons', + '500': 'Internal Server Error', + '501': 'Not Implemented', + '502': 'Bad Gateway', + '503': 'Service Unavailable', + '504': 'Gateway Timeout', + '505': 'HTTP Version Not Supported', + '506': 'Variant Also Negotiates', + '507': 'Insufficient Storage', + '508': 'Loop Detected', + '509': 'Bandwidth Limit Exceeded', + '510': 'Not Extended', + '511': 'Network Authentication Required', +}; diff --git a/package.json b/package.json new file mode 100644 index 0000000..d6ac26a --- /dev/null +++ b/package.json @@ -0,0 +1,54 @@ +{ + "name": "deadmanssnitch-client", + "description": "A library for interacting with the Dead Man's Snitch API", + "version": "1.0.0", + "main": "./lib/index.js", + "keywords": [ + "deadmans snitch", + "deadmans", + "snitch", + "monitoring", + "check-in", + "devops", + "rest", + "api" + ], + "repository": { + "type": "git", + "url": "https://github.com/pauldenver/deadmanssnitch-client.git" + }, + "author": "Paul Proctor ", + "scripts": { + "lint": "eslint ./lib/**/*.js", + "lint:fix": "eslint ./lib/**/*.js --fix", + "test": "mocha ./test/tests.js", + "test:coverage": "nyc --reporter=html --reporter=text mocha ./test/tests.js", + "test:coveralls": "nyc report --reporter=text-lcov | coveralls", + "test:codecov": "nyc report --reporter=text-lcov | codecov --pipe" + }, + "dependencies": { + "axios": "^0.19.2", + "lodash.has": "^4.5.2", + "lodash.isempty": "^4.4.0", + "lodash.isobjectlike": "^4.0.0", + "lodash.isplainobject": "^4.0.6" + }, + "devDependencies": { + "chai": "^4.2.0", + "chai-as-promised": "^7.1.1", + "codecov": "^3.6.5", + "coveralls": "^3.0.11", + "eslint": "^6.8.0", + "eslint-config-google": "^0.14.0", + "eslint-plugin-import": "^2.20.2", + "mocha": "^7.1.1", + "nock": "^12.0.3", + "nyc": "^15.0.1", + "random-sentence": "^1.0.4", + "rewire": "^5.0.0" + }, + "engines": { + "node": ">= 8.0.0" + }, + "license": "Apache-2.0" +} diff --git a/test/deadmanssnitch_client.test.js b/test/deadmanssnitch_client.test.js new file mode 100644 index 0000000..b800ade --- /dev/null +++ b/test/deadmanssnitch_client.test.js @@ -0,0 +1,1093 @@ +const chai = require('chai'); +const chaiAsPromised = require('chai-as-promised'); +const rewire = require('rewire'); +const nock = require('nock'); +const DeadMansSnitchClient = require('../lib'); +const { getMockSnitches, getMockToken } = require('./helpers'); + +// Use 'chai-as-promised'. +chai.use(chaiAsPromised); +// Get 'expect'. +const expect = chai.expect; + +const clientRewire = rewire('../lib/deadmanssnitch_client'); +const apiBaseUrl = clientRewire.__get__('API_BASE_URL'); +const checkInBaseUrl = clientRewire.__get__('CHECKIN_BASE_URL'); +const userAgent = clientRewire.__get__('USER_AGENT'); + +describe(`Dead Man's Snitch Client Tests`, () => { + let client; + + const clientOptions = { + apiKey: 'vX7nv5RtIIPfMU9U1p4G8k' + }; + + beforeEach(() => { + client = new DeadMansSnitchClient(clientOptions); + }); + + context(`'DeadMansSnitchClient' Class instance`, () => { + it(`should be an instance of 'DeadMansSnitchClient'`, () => { + expect(client).to.be.an('object'); + expect(client).to.be.an.instanceof(DeadMansSnitchClient); + }); + + it(`should have a public 'constructor' method`, () => { + expect(client.constructor).to.be.an('function'); + expect(client.constructor).to.be.an.instanceof(Function); + }); + + it(`should have a private '_getApiKey' method`, () => { + expect(client._getApiKey).to.be.an('function'); + expect(client._getApiKey).to.be.an.instanceof(Function); + }); + + it(`should have a private '_checkApiKey' method`, () => { + expect(client._checkApiKey).to.be.an('function'); + expect(client._checkApiKey).to.be.an.instanceof(Function); + }); + + it(`should have a private '_getRequestHeaders' method`, () => { + expect(client._getRequestHeaders).to.be.an('function'); + expect(client._getRequestHeaders).to.be.an.instanceof(Function); + }); + + it(`should have a private '_getAxiosInstance' method`, () => { + expect(client._getAxiosInstance).to.be.an('function'); + expect(client._getAxiosInstance).to.be.an.instanceof(Function); + }); + + it(`should have a private '_getRequestOptions' method`, () => { + expect(client._getRequestOptions).to.be.an('function'); + expect(client._getRequestOptions).to.be.an.instanceof(Function); + }); + + it(`should have a private '_performRequest' method`, () => { + expect(client._performRequest).to.be.an('function'); + expect(client._performRequest).to.be.an.instanceof(Function); + }); + + it(`should have a private '_handleError' method`, () => { + expect(client._handleError).to.be.an('function'); + expect(client._handleError).to.be.an.instanceof(Function); + }); + + it(`should have a private '_processCallback' method`, () => { + expect(client._processCallback).to.be.an('function'); + expect(client._processCallback).to.be.an.instanceof(Function); + }); + + it(`should have a public 'checkIn' method`, () => { + expect(client.checkIn).to.be.an('function'); + expect(client.checkIn).to.be.an.instanceof(Function); + }); + + it(`should have a public 'getSnitches' method`, () => { + expect(client.getSnitches).to.be.an('function'); + expect(client.getSnitches).to.be.an.instanceof(Function); + }); + + it(`should have a public 'filterByStatus' method`, () => { + expect(client.filterByStatus).to.be.an('function'); + expect(client.filterByStatus).to.be.an.instanceof(Function); + }); + + it(`should have a public 'filterByInterval' method`, () => { + expect(client.filterByInterval).to.be.an('function'); + expect(client.filterByInterval).to.be.an.instanceof(Function); + }); + + it(`should have a public 'filterByAlertType' method`, () => { + expect(client.filterByAlertType).to.be.an('function'); + expect(client.filterByAlertType).to.be.an.instanceof(Function); + }); + + it(`should have a public 'getSnitch' method`, () => { + expect(client.getSnitch).to.be.an('function'); + expect(client.getSnitch).to.be.an.instanceof(Function); + }); + + it(`should have a public 'createSnitch' method`, () => { + expect(client.createSnitch).to.be.an('function'); + expect(client.createSnitch).to.be.an.instanceof(Function); + }); + + it(`should have a public 'updateSnitch' method`, () => { + expect(client.updateSnitch).to.be.an('function'); + expect(client.updateSnitch).to.be.an.instanceof(Function); + }); + + it(`should have a public 'addTags' method`, () => { + expect(client.addTags).to.be.an('function'); + expect(client.addTags).to.be.an.instanceof(Function); + }); + + it(`should have a public 'removeTag' method`, () => { + expect(client.removeTag).to.be.an('function'); + expect(client.removeTag).to.be.an.instanceof(Function); + }); + + it(`should have a public 'changeTags' method`, () => { + expect(client.changeTags).to.be.an('function'); + expect(client.changeTags).to.be.an.instanceof(Function); + }); + + it(`should have a public 'removeAllTags' method`, () => { + expect(client.removeAllTags).to.be.an('function'); + expect(client.removeAllTags).to.be.an.instanceof(Function); + }); + + it(`should have a public 'pauseSnitch' method`, () => { + expect(client.pauseSnitch).to.be.an('function'); + expect(client.pauseSnitch).to.be.an.instanceof(Function); + }); + + it(`should have a public 'deleteSnitch' method`, () => { + expect(client.deleteSnitch).to.be.an('function'); + expect(client.deleteSnitch).to.be.an.instanceof(Function); + }); + }); + + context('#constructor()', () => { + it(`should have a private '_options' property`, () => { + expect(client).to.have.property('_options'); + expect(client._options).to.be.an('object'); + expect(client._options).to.eql(clientOptions); + }); + + it(`should have a private '_apiKey' property`, () => { + const otherClient = new DeadMansSnitchClient(); + + expect(client).to.have.property('_apiKey'); + expect(client._apiKey).to.be.a('string'); + expect(client._apiKey).to.eql(clientOptions.apiKey); + expect(otherClient).to.have.property('_apiKey'); + expect(otherClient._apiKey).to.be.undefined; + }); + + it(`should throw an error when given a non-object for options`, () => { + expect(() => new DeadMansSnitchClient([])).to.throw(TypeError); + expect(() => new DeadMansSnitchClient('test')).to.throw(TypeError); + expect(() => new DeadMansSnitchClient(999)).to.throw(TypeError); + }); + }); + + context('#_getApiKey()', () => { + it(`should return the API key from the options`, () => { + const apiKey = client._getApiKey(clientOptions); + + expect(apiKey).to.be.a('string'); + expect(apiKey).to.eql(clientOptions.apiKey); + }); + + it(`should return the API key from the environment variables`, () => { + process.env.DMS_API_KEY = 'TEST-API-KEY'; + const apiKey = client._getApiKey({}); + + expect(apiKey).to.be.a('string'); + expect(apiKey).to.eql(process.env.DMS_API_KEY); + + delete process.env.DMS_API_KEY; + }); + }); + + context('#_checkApiKey()', () => { + it(`should not throw an error when '_apiKey' is present`, () => { + expect(() => client._checkApiKey()).to.not.throw(); + }); + + it(`should throw an error when missing '_apiKey'`, () => { + expect(() => { + client._apiKey = undefined; + client._checkApiKey(); + }).to.throw(Error); + }); + }); + + context('#_getRequestHeaders()', () => { + it('should get the check-in request headers', () => { + const expectedHeaders = { + 'Accept': 'text/plain; charset=utf-8', + 'Content-Type': 'text/plain; charset=utf-8', + 'User-Agent': userAgent, + }; + + const headers = client._getRequestHeaders(checkInBaseUrl); + + expect(headers).to.be.an('object'); + expect(headers).to.eql(expectedHeaders); + }); + + it('should get the API request headers', () => { + const expectedHeaders = { + 'Accept': 'application/json; charset=utf-8', + 'Content-Type': 'application/json; charset=utf-8', + 'User-Agent': userAgent, + }; + + const headers = client._getRequestHeaders(apiBaseUrl); + + expect(headers).to.be.an('object'); + expect(headers).to.eql(expectedHeaders); + }); + }); + + context('#_getRequestOptions()', () => { + it('should get the request options without query parameters or body', () => { + // Get the options. + const options = client._getRequestOptions('GET', '/v1/snitches'); + + expect(options).to.be.an('object'); + expect(options).to.have.property('url', '/v1/snitches'); + expect(options).to.have.property('method', 'GET'); + expect(options.params).to.be.undefined; + expect(options.data).to.be.undefined; + }); + + it('should get the request options with query parameters and without a body', () => { + const query = { + tags: 'prod,app' + }; + + // Get the options. + const options = client._getRequestOptions('GET', + '/v1/snitches', query); + + expect(options).to.be.an('object'); + expect(options).to.have.property('url', '/v1/snitches'); + expect(options).to.have.property('method', 'GET'); + expect(options).to.have.property('params'); + expect(options.params).to.be.an('object'); + expect(options.params).to.eql(query); + expect(options.data).to.be.undefined; + }); + + it('should get the request options with a body and without query parameters', () => { + const body = [ 'prod', 'app', 'www' ]; + + // Get the options. + const options = client._getRequestOptions('POST', + '/v1/snitches/some-token-here/tags', null, body); + + expect(options).to.be.an('object'); + expect(options).to.have.property('url', + '/v1/snitches/some-token-here/tags'); + expect(options).to.have.property('method', 'POST'); + expect(options).to.have.property('data'); + expect(options.data).to.be.an('array'); + expect(options.data).to.eql(body); + expect(options.params).to.be.undefined; + }); + }); + + context('#_performRequest()', () => { + const token = getMockToken(); + + const checkInResponse = 'Got it, thanks!\n'; + + const checkInFullResponse = { + statusCode: 202, + statusMessage: 'Accepted', + headers: {}, + data: checkInResponse + }; + + const apiResponse = getMockSnitches(1, [ 'golden', 'snitch' ])[0]; + + const apiFullResponse = { + statusCode: 200, + statusMessage: 'OK', + headers: { 'content-type': 'application/json' }, + data: apiResponse, + }; + + it(`should return a Dead Man's Snitch check-in response`, async () => { + // Mock the API request. + nock(checkInBaseUrl) + .get(`/${token}`) + .reply(202, checkInResponse); + + // Get the options. + const options = client._getRequestOptions('GET', `/${token}`); + + // Perform the request. + const resp = await client._performRequest('check-in', options); + + expect(resp).to.be.a('string'); + expect(resp).to.eql(checkInResponse); + + nock.cleanAll(); + }); + + it(`should return a full Dead Man's Snitch check-in response`, async () => { + // Mock the API request. + nock(checkInBaseUrl) + .get(`/${token}`) + .reply(202, checkInResponse); + + // Set the full response option. + client.fullResponse = true; + + // Get the options. + const options = client._getRequestOptions('GET', `/${token}`); + + // Perform the request. + const resp = await client._performRequest('check-in', options); + + expect(resp).to.be.an('object'); + expect(resp).to.have.property('statusCode'); + expect(resp).to.have.property('statusMessage'); + expect(resp).to.have.property('headers'); + expect(resp).to.have.property('data'); + expect(resp).to.eql(checkInFullResponse); + + nock.cleanAll(); + }); + + it(`should return a Dead Man's Snitch API response`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get(`/v1/snitches/${apiResponse.token}`) + .reply(200, apiResponse); + + // Get the options. + const options = client._getRequestOptions('GET', + `/v1/snitches/${apiResponse.token}`); + + // Perform the request. + const snitch = await client._performRequest('api', options); + + expect(snitch).to.be.an('object'); + expect(snitch).to.eql(apiResponse); + + nock.cleanAll(); + }); + + it(`should return a full Dead Man's Snitch API response`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get(`/v1/snitches/${apiResponse.token}`) + .reply(200, apiResponse); + + // Set the full response option. + client.fullResponse = true; + + // Get the options. + const options = client._getRequestOptions('GET', + `/v1/snitches/${apiResponse.token}`); + + // Perform the request. + const resp = await client._performRequest('api', options); + + expect(resp).to.be.an('object'); + expect(resp).to.have.property('statusCode'); + expect(resp).to.have.property('statusMessage'); + expect(resp).to.have.property('headers'); + expect(resp).to.have.property('data'); + expect(resp).to.eql(apiFullResponse); + + nock.cleanAll(); + }); + + it('should throw an error when missing the request options', async () => { + await expect(client._performRequest('api', undefined)).to.be.rejectedWith(Error); + await expect(client._performRequest('api', 'something')).to.be.rejectedWith(Error); + await expect(client._performRequest('api', [])).to.be.rejectedWith(Error); + await expect(client._performRequest('api', {})).to.be.rejectedWith(Error); + }); + + it('should throw an error for an invalid request type', async () => { + await expect( + client._performRequest('something', { method: 'GET' }) + ).to.be.rejectedWith(Error); + }); + }); + + context('#_handleError()', () => { + it(`should return a 'StatusCodeError' error`, () => { + const statusCode = 403; + const statusText = 'Authentication failed or rate-limit reached'; + + const err = new Error(`Request failed with status code ${statusCode}`); + + // Mock Axios response object. + err.response = { + status: statusCode, + statusText, + headers: {}, + data: 'Bad stuff', + }; + + // Add the typical Axios error values. + err.code = null; + err.config = {}; + err.request = {}; + err.isAxiosError = true; + err.toJSON = () => {}; + + // Create the error. + const handledErr = client._handleError(err); + + expect(handledErr).to.be.an.instanceof(Error); + expect(handledErr.name).to.eql('StatusCodeError'); + expect(handledErr.message).to.eql(String(err)); + expect(handledErr.statusCode).to.eql(statusCode); + expect(handledErr.statusMessage).to.eql(statusText); + expect(handledErr.headers).to.eql({}); + expect(handledErr.body).to.eql('Bad stuff'); + expect(handledErr).to.have.property('cause'); + expect(handledErr.cause).to.be.an.instanceof(Error); + expect(handledErr.cause.message).to.eql(err.message); + }); + + it(`should return a 'RequestError' error`, () => { + const err = new Error('Oops, something happened'); + err.config = {}; + err.response = undefined; + + // Create the error. + const handledErr = client._handleError(err); + + expect(handledErr).to.be.an.instanceof(Error); + expect(handledErr.name).to.eql('RequestError'); + expect(handledErr.message).to.eql(String(err)); + expect(handledErr).to.have.property('cause'); + expect(handledErr.cause).to.be.an.instanceof(Error); + expect(handledErr.cause.message).to.eql(err.message); + }); + + it(`should return an unmodified error`, () => { + const err = new Error('Oops, something happened'); + + // Create the error. + const handledErr = client._handleError(err); + + expect(handledErr).to.be.an.instanceof(Error); + expect(handledErr).to.eql(err); + }); + }); + + context('#_processCallback()', () => { + it(`should execute the provided callback function`, () => { + let callbackCalled = false; + + // Setup the callback. + const callbackFunc = (err, resp) => { + callbackCalled = true; + expect(err).to.be.undefined; + expect(resp).to.eql('Some data'); + }; + + client._processCallback(undefined, 'Some data', callbackFunc); + + expect(callbackCalled).to.be.true; + }); + + it(`should return the response when not provided a callback function`, () => { + const resp = client._processCallback(undefined, 'Some data'); + expect(resp).to.eql('Some data'); + }); + + it(`should throw an error when not provided a response or callback function`, () => { + expect(() => { + client._processCallback(new Error('Some error')); + }).to.throw(Error); + }); + }); + + context('#checkIn()', () => { + const token = getMockToken(); + const response = 'Got it, thanks!\n'; + + it(`should perform a snitch check-in`, async () => { + // Mock the API request. + nock(checkInBaseUrl) + .get(`/${token}`) + .reply(202, response); + + const resp = await client.checkIn(token); + + expect(resp).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should perform a snitch check-in with a string message`, async () => { + // Mock the API request. + nock(checkInBaseUrl) + .get(`/${token}?m=test+message`) + .reply(202, response); + + const resp = await client.checkIn(token, 'test message'); + + expect(resp).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should perform a snitch check-in with an object message`, async () => { + const obj = { + type: 'important', + data: { + value: 'Something special' + } + }; + + // Mock the API request. + nock(checkInBaseUrl) + .get(`/${token}?m=${encodeURIComponent(JSON.stringify(obj))}`) + .reply(202, response); + + const resp = await client.checkIn(token, obj); + + expect(resp).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when performing a snitch check-in`, async () => { + // Mock the API request. + nock(checkInBaseUrl) + .get('/other-token') + .replyWithError('Something bad happened!'); + + await expect(client.checkIn('other-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#getSnitches()', () => { + const prodSnitches = getMockSnitches(2, [ 'prod' ]); + const appWwwSnitches = getMockSnitches(3, [ 'app', 'www' ]); + + const response = [ + ...prodSnitches, + ...appWwwSnitches, + ]; + + it(`should return a list of snitches`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .times(3) + .reply(200, response); + + let snitches = await client.getSnitches(); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(response); + + snitches = await client.getSnitches({}); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(response); + + snitches = await client.getSnitches([ 1, 2, 3 ]); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should return a list of snitches by tags`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches?tags=prod') + .reply(200, prodSnitches) + .get('/v1/snitches?tags=app,www') + .reply(200, appWwwSnitches); + + let snitches = await client.getSnitches([ 'prod' ]); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(prodSnitches); + + snitches = await client.getSnitches([ 'app', 'www' ]); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(appWwwSnitches); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when performing a snitch check-in`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .replyWithError('Something bad happened!'); + + await expect(client.getSnitches()).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#filterByStatus()', () => { + const failedSnitches = getMockSnitches(2, [ 'prod' ], 'failed'); + const healthySnitches = getMockSnitches(4, [ 'prod' ], 'healthy'); + + const response = [ + ...failedSnitches, + ...healthySnitches, + ]; + + it(`should return snitches filtered by status`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .reply(200, response); + + const snitches = await client.filterByStatus('failed'); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(failedSnitches); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when given an invalid status value`, async () => { + await expect(client.filterByStatus('bad')).to.be.rejectedWith(Error); + await expect(client.filterByStatus({})).to.be.rejectedWith(Error); + }); + + it(`should throw an error when getting filtered snitches`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .replyWithError('Something bad happened!'); + + await expect(client.filterByStatus('paused')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#filterByInterval()', () => { + const dailySnitches = getMockSnitches(2, [ 'prod' ], 'healthy', 'daily'); + const weeklySnitches = getMockSnitches(4, [ 'prod' ], 'healthy', 'weekly'); + + const response = [ + ...dailySnitches, + ...weeklySnitches, + ]; + + it(`should return snitches filtered by interval`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .reply(200, response); + + const snitches = await client.filterByInterval('daily'); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(dailySnitches); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when given an invalid interval value`, async () => { + await expect(client.filterByInterval('bad')).to.be.rejectedWith(Error); + await expect(client.filterByInterval({})).to.be.rejectedWith(Error); + }); + + it(`should throw an error when getting filtered snitches`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .replyWithError('Something bad happened!'); + + await expect(client.filterByInterval('monthly')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#filterByAlertType()', () => { + const smartSnitches = getMockSnitches(3, [ 'prod' ], 'healthy', 'daily', 'smart'); + const basicSnitches = getMockSnitches(6, [ 'prod' ], 'healthy', 'daily', 'basic'); + + const response = [ + ...smartSnitches, + ...basicSnitches, + ]; + + it(`should return snitches filtered by alert type`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .reply(200, response); + + const snitches = await client.filterByAlertType('smart'); + + expect(snitches).to.be.an('array'); + expect(snitches).to.eql(smartSnitches); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when given an invalid alert type value`, async () => { + await expect(client.filterByAlertType('bad')).to.be.rejectedWith(Error); + await expect(client.filterByAlertType({})).to.be.rejectedWith(Error); + }); + + it(`should throw an error when getting filtered snitches`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches') + .replyWithError('Something bad happened!'); + + await expect(client.filterByAlertType('basic')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#getSnitch()', () => { + const response = getMockSnitches(1, [ 'dev' ])[0]; + + it(`should return information for a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get(`/v1/snitches/${response.token}`) + .reply(200, response); + + const snitch = await client.getSnitch(response.token); + + expect(snitch).to.be.an('object'); + expect(snitch).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when getting a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .get('/v1/snitches/not-a-valid-token') + .replyWithError('Something bad happened!'); + + await expect(client.getSnitch('not-a-valid-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#createSnitch()', () => { + const response = getMockSnitches(1, [ 'dev' ])[0]; + + it(`should create a new snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post('/v1/snitches') + .reply(200, response); + + const snitch = await client.createSnitch({ + name: response.name, + interval: response.interval, + }); + + expect(snitch).to.be.an('object'); + expect(snitch).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when creating a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post('/v1/snitches') + .replyWithError('Something bad happened!'); + + await expect(client.createSnitch()).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#updateSnitch()', () => { + const response = getMockSnitches(1, [ 'prod', 'app' ], undefined, + 'monthly')[0]; + + it(`should update an existing snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .patch(`/v1/snitches/${response.token}`) + .reply(200, response); + + const snitch = await client.updateSnitch(response.token, { + tags: response.tags, + interval: response.interval, + }); + + expect(snitch).to.be.an('object'); + expect(snitch).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when updating a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .patch('/v1/snitches/not-a-valid-token') + .replyWithError('Something bad happened!'); + + await expect( + client.updateSnitch('not-a-valid-token') + ).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#addTags()', () => { + const token = getMockToken(); + + const response = [ 'prod', 'app', 'www' ]; + + it(`should add tags to an existing snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post(`/v1/snitches/${token}/tags`) + .reply(200, response); + + const resp = await client.addTags(token, [ 'www' ]); + + expect(resp).to.be.an('array'); + expect(resp).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when adding tags to a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post('/v1/snitches/not-a-valid-token/tags') + .replyWithError('Something bad happened!'); + + await expect(client.addTags('not-a-valid-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#addTags()', () => { + const token = getMockToken(); + + const response = [ 'prod', 'app', 'www' ]; + + it(`should add tags to an existing snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post(`/v1/snitches/${token}/tags`) + .reply(200, response); + + const resp = await client.addTags(token, [ 'www' ]); + + expect(resp).to.be.an('array'); + expect(resp).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when adding tags to a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post('/v1/snitches/not-a-valid-token/tags') + .replyWithError('Something bad happened!'); + + await expect(client.addTags('not-a-valid-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#removeTag()', () => { + const token = getMockToken(); + + const response = [ 'prod', 'app' ]; + + it(`should delete a tag from an existing snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .delete(`/v1/snitches/${token}/tags/www`) + .reply(200, response); + + const resp = await client.removeTag(token, 'www'); + + expect(resp).to.be.an('array'); + expect(resp).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when deleting a snitch tag`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .delete('/v1/snitches/not-a-valid-token/tags/www') + .replyWithError('Something bad happened!'); + + await expect( + client.removeTag('not-a-valid-token', 'www') + ).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#changeTags()', () => { + const response = getMockSnitches(1, [ 'dev', 'special' ])[0]; + + it(`should replace the tags of an existing snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .patch(`/v1/snitches/${response.token}`) + .reply(200, response); + + const snitch = await client.changeTags(response.token, response.tags); + + expect(snitch).to.be.an('object'); + expect(snitch).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when given invalid tags`, async () => { + await expect(client.changeTags(response.token)).to.be.rejectedWith(Error); + await expect(client.changeTags(response.token, {})).to.be.rejectedWith(Error); + }); + + it(`should throw an error when replacing the tags of a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .patch('/v1/snitches/not-a-valid-token') + .replyWithError('Something bad happened!'); + + await expect( + client.changeTags('not-a-valid-token', [ 'www' ]) + ).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#removeAllTags()', () => { + const response = getMockSnitches(1, [])[0]; + + it(`should delete all tags from an existing snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .patch(`/v1/snitches/${response.token}`) + .reply(200, response); + + const snitch = await client.removeAllTags(response.token); + + expect(snitch).to.be.an('object'); + expect(snitch).to.eql(response); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when deleting the tags from a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .patch('/v1/snitches/not-a-valid-token') + .replyWithError('Something bad happened!'); + + await expect(client.removeAllTags('not-a-valid-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#pauseSnitch()', () => { + const token = getMockToken(); + + it(`should pause a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post(`/v1/snitches/${token}/pause`) + .reply(204, ''); + + const resp = await client.pauseSnitch(token); + + expect(resp).to.be.a('string'); + expect(resp).to.eql(''); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when pausing a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .post('/v1/snitches/not-a-valid-token/pause') + .replyWithError('Something bad happened!'); + + await expect(client.pauseSnitch('not-a-valid-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); + + context('#deleteSnitch()', () => { + const token = getMockToken(); + + it(`should delete a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .delete(`/v1/snitches/${token}`) + .reply(204, ''); + + const resp = await client.deleteSnitch(token); + + expect(resp).to.be.a('string'); + expect(resp).to.eql(''); + + // Remove the mocks. + nock.cleanAll(); + }); + + it(`should throw an error when deleting a snitch`, async () => { + // Mock the API request. + nock(apiBaseUrl) + .delete('/v1/snitches/not-a-valid-token') + .replyWithError('Something bad happened!'); + + await expect(client.deleteSnitch('not-a-valid-token')).to.be.rejectedWith(Error); + + // Remove the mocks. + nock.cleanAll(); + }); + }); +}); \ No newline at end of file diff --git a/test/helpers.js b/test/helpers.js new file mode 100644 index 0000000..b92b16b --- /dev/null +++ b/test/helpers.js @@ -0,0 +1,105 @@ +const randomSentence = require('random-sentence'); + +// Status values for snitches. +const SNITCH_STATUSES = [ + 'pending', + 'healthy', + 'failed', + 'errored', + 'paused', +]; + +// Interval values for snitches. +const SNITCH_INTERVALS = [ + '15_minute', + '30_minute', + 'hourly', + 'daily', + 'weekly', + 'monthly', +]; + +// Alert type values for snitches. +const SNITCH_ALERT_TYPES = [ 'basic', 'smart' ]; + +/** + * Generates a random snitch token. + * + * @returns {String} The snitch token. + */ +function getMockToken() { + return Math.random().toString(36).substr(2, 5) + + Math.random().toString(36).substr(2, 5); +} + +/** + * Gets an ISO string from a random date generated + * from a starting date and end date. + * + * @param {Date} start Start date. + * @param {Date} end End date. + * @returns {String} Date string + */ +function getRandomDate(start, end) { + const randomDate = new Date(start.getTime() + Math.random() * + (end.getTime() - start.getTime())); + return randomDate.toISOString(); +} + +/** + * Generates a random number. + * + * @param {Number} total Max number. + * @returns {Number} Random number. + */ +function getRandomNumber(total) { + return Math.floor(Math.random() * total); +} + +/** + * Creates an array of mock snitch values. + * + * @param {Number} total Total number of snitches. + * @param {Array} [tags=[]] Snitch tags. + * @param {String} status Snitch status. + * @param {String} interval Snitch interval. + * @param {String} alertType Snitch alert type. + * @returns {Array} Mock snitches. + */ +function getMockSnitches(total, tags = [], status, interval, alertType) { + const snitches = []; + + for (let i = 0; i < total; i++ ) { + const token = getMockToken(); + status = (status || + SNITCH_STATUSES[getRandomNumber(SNITCH_STATUSES.length)]); + interval = (interval || + SNITCH_INTERVALS[getRandomNumber(SNITCH_INTERVALS.length)]); + alertType = (alertType || + SNITCH_ALERT_TYPES[getRandomNumber(SNITCH_ALERT_TYPES.length)]); + + snitches.push({ + token, + href: `/v1/snitches/${token}`, + name: randomSentence({ min: 3, max: 8 }), + tags, + notes: randomSentence({ min: 8, max: 12 }), + status, + created_at: getRandomDate(new Date(2019, 0, 1), new Date(2020, 0, 1)), + check_in_url: `https://nosnch.in/${token}`, + checked_in_at: getRandomDate(new Date(2020, 0, 1), new Date()), + type: { + interval, + }, + interval, + alert_type: alertType, + }); + } + + return snitches; +} + +module.exports = { + getMockToken, + getMockSnitches, +}; \ No newline at end of file diff --git a/test/tests.js b/test/tests.js new file mode 100644 index 0000000..aa56477 --- /dev/null +++ b/test/tests.js @@ -0,0 +1,2 @@ +require('./deadmanssnitch_client.test.js'); +require('./utils/errors.test.js'); \ No newline at end of file diff --git a/test/utils/errors.test.js b/test/utils/errors.test.js new file mode 100644 index 0000000..60ccd77 --- /dev/null +++ b/test/utils/errors.test.js @@ -0,0 +1,203 @@ +const { expect } = require('chai'); +const { + RequestError, + StatusCodeError, + isAxiosRequestError, + isAxiosResponseError +} = require('../../lib/utils/errors'); +const status = require('../../lib/utils/status'); + +describe('Errors Util Tests', () => { + describe('RequestError Class', () => { + let requestErr; + + const err = new Error('Oops, something happened'); + err.config = {}; + err.response = undefined; + + beforeEach(() => { + requestErr = new RequestError(err); + }); + + context(`'RequestError' Class instance`, () => { + it(`should be an instance of 'RequestError'`, () => { + expect(requestErr).to.be.an.instanceof(Error); + expect(requestErr).to.be.an.instanceof(RequestError); + }); + + it(`should have a public 'constructor' method`, () => { + expect(requestErr.constructor).to.be.an('function'); + expect(requestErr.constructor).to.be.an.instanceof(Function); + }); + }); + + context('#constructor()', () => { + it(`should have a public 'name' property`, () => { + expect(requestErr).to.have.property('name'); + expect(requestErr.name).to.be.a('string'); + expect(requestErr.name).to.eql('RequestError'); + }); + + it(`should have a public 'message' property`, () => { + expect(requestErr).to.have.property('message'); + expect(requestErr.message).to.be.a('string'); + expect(requestErr.message).to.eql(String(err)); + }); + + it(`should have a public 'cause' property`, () => { + expect(requestErr).to.have.property('cause'); + expect(requestErr.cause).to.be.an.instanceof(Error); + expect(requestErr.cause.message).to.eql(err.message); + }); + }); + }); + + describe('StatusCodeError Class', () => { + let statusCodeErr; + let err; + + const statusCode = 403; + const statusText = 'Authentication failed or rate-limit reached'; + + const getRespError = () => { + err = new Error(`Request failed with status code ${statusCode}`); + + // Mock Axios response object. + err.response = { + status: statusCode, + statusText, + headers: {}, + data: 'Bad stuff', + }; + + // Add the typical Axios error values. + err.code = null; + err.config = {}; + err.request = {}; + err.isAxiosError = true; + err.toJSON = () => {}; + }; + + beforeEach(() => { + getRespError(); + statusCodeErr = new StatusCodeError(err); + }); + + context(`'StatusCodeError' Class instance`, () => { + it(`should be an instance of 'StatusCodeError'`, () => { + expect(statusCodeErr).to.be.an.instanceof(Error); + expect(statusCodeErr).to.be.an.instanceof(StatusCodeError); + }); + + it(`should have a public 'constructor' method`, () => { + expect(statusCodeErr.constructor).to.be.an('function'); + expect(statusCodeErr.constructor).to.be.an.instanceof(Function); + }); + }); + + context('#constructor()', () => { + it(`should have a public 'name' property`, () => { + expect(statusCodeErr).to.have.property('name'); + expect(statusCodeErr.name).to.be.a('string'); + expect(statusCodeErr.name).to.eql('StatusCodeError'); + }); + + it(`should have a public 'message' property`, () => { + expect(statusCodeErr).to.have.property('message'); + expect(statusCodeErr.message).to.be.a('string'); + expect(statusCodeErr.message).to.eql(String(err)); + }); + + it(`should have a public 'statusCode' property`, () => { + expect(statusCodeErr).to.have.property('statusCode'); + expect(statusCodeErr.statusCode).to.be.a('number'); + expect(statusCodeErr.statusCode).to.eql(statusCode); + }); + + it(`should have a public 'statusMessage' property`, () => { + expect(statusCodeErr).to.have.property('statusMessage'); + expect(statusCodeErr.statusMessage).to.be.a('string'); + expect(statusCodeErr.statusMessage).to.eql(statusText); + + // Create an instance without a 'statusText' property. + getRespError(); + delete err.response.statusText; + statusCodeErr = new StatusCodeError(err); + + expect(statusCodeErr.statusMessage).to.eql(status[statusCode]); + }); + + it(`should have a public 'headers' property`, () => { + expect(statusCodeErr).to.have.property('headers'); + expect(statusCodeErr.headers).to.be.an('object'); + expect(statusCodeErr.headers).to.eql({}); + }); + + it(`should have a public 'body' property`, () => { + expect(statusCodeErr).to.have.property('body'); + expect(statusCodeErr.body).to.be.a('string'); + expect(statusCodeErr.body).to.eql('Bad stuff'); + }); + + it(`should have a public 'cause' property`, () => { + expect(statusCodeErr).to.have.property('cause'); + expect(statusCodeErr.cause).to.be.an.instanceof(Error); + expect(statusCodeErr.cause.message).to.eql(err.message); + }); + }); + }); + + describe('#isAxiosRequestError()', () => { + // Create the request error. + const err = new Error('Oops, something happened'); + err.config = {}; + err.response = undefined; + + it('should return true for a valid request error', () => { + // Get the result. + const result = isAxiosRequestError(err); + + expect(result).to.be.a('boolean'); + expect(result).to.be.true; + }); + + it('should return false for an invalid request error', () => { + // Add a response value. + err.response = { + status: 200, + }; + + // Get the result. + const result = isAxiosRequestError(err); + + expect(result).to.be.a('boolean'); + expect(result).to.be.false; + }); + }); + + describe('#isAxiosResponseError()', () => { + // Create the response error. + const err = new Error('Oops, something happened'); + err.response = { + status: 200, + }; + + it('should return true for a valid response error', () => { + // Get the result. + const result = isAxiosResponseError(err); + + expect(result).to.be.a('boolean'); + expect(result).to.be.true; + }); + + it('should return false for an invalid response error', () => { + err.response.status = undefined; + + // Get the result. + const result = isAxiosResponseError(err); + + expect(result).to.be.a('boolean'); + expect(result).to.be.false; + }); + }); +}); \ No newline at end of file