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