npm package: @novigi/api
Description: Simple and lightweight Javascript Promise based API wrapper for Nodejs native https module 🍁
Author: Novigi
Latest version: 1.0.0-0

![npm (scoped)](https://img.shields.io/npm/v/@novigi/api) ![NPM](https://img.shields.io/npm/l/@novigi/api) ![Statements](https://img.shields.io/badge/statements-97.98%25-brightgreen.svg?style=flat) ![Branches](https://img.shields.io/badge/branches-94%25-brightgreen.svg?style=flat) ![Functions](https://img.shields.io/badge/functions-96.87%25-brightgreen.svg?style=flat) ![Lines](https://img.shields.io/badge/lines-97.95%25-brightgreen.svg?style=flat)
# @novigi/api

Simple and lightweight Javascript Promise based API wrapper for Nodejs native https module 🍁

## 🐿 Features

- Chainable and immutable API
- Simple code to wrap HTTP calls with native and bulky `https` module
- Supports multipart/form-data submissions → with `form` method
- Invoking a backend API with customized headers

## 📦 Getting Started

1. Install the dependency
```
npm install @novigi/api
```

2. Import the library
```
const lib = require('@novigi/api');
```

## 📖 Documentation

<a name="module_api"></a>

## api
This library contains methods to asynchronously invoke HTTP and HTTPS endpoints.

```js
const api = require('@novigi/api')


const main = api("https://api.call")  // returns new `Api` object

try {
   let response = await main.header('Authorization', 'Bearer NksdfnIU')
                          .get()
                          .response()
} catch (err) {
   console.error(err)
}

// or

let response = await main.headers({'Authorization': 'Bearer NksdfnIU'})
                       .onStatusPattern('4[0-9]{2}', (response) => console.error(response))
                       .body({ 'posting': 'data'})
                       .post('/v2/blog')
                       .response()
                       .catch((err) => console.error(err))

// response => { headers: {...}, body: 'response' }

```

Chainable + immutable methods! ☝


* [api](#module_api)
    * [~Api](#module_api..Api)
        * [.header](#module_api..Api+header) ⇒ <code>Api</code>
        * [.headers](#module_api..Api+headers) ⇒ <code>Api</code>
        * [.httpOptions](#module_api..Api+httpOptions) ⇒ <code>Api</code>
        * [.response](#module_api..Api+response) ⇒ <code>Promise.&lt;HttpResponse&gt;</code>
        * [.json](#module_api..Api+json) ⇒ <code>Promise.&lt;object&gt;</code>
        * [.get](#module_api..Api+get) ⇒ <code>Api</code>
        * [.post](#module_api..Api+post) ⇒ <code>Api</code>
        * [.put](#module_api..Api+put) ⇒ <code>Api</code>
        * [.patch](#module_api..Api+patch) ⇒ <code>Api</code>
        * [.delete](#module_api..Api+delete) ⇒ <code>Api</code>
        * [.method](#module_api..Api+method) ⇒ <code>Api</code>
        * [.body](#module_api..Api+body) ⇒ <code>Api</code>
        * [.form](#module_api..Api+form) ⇒ <code>Api</code>
        * [.attach](#module_api..Api+attach) ⇒ <code>Api</code>
        * [.onStatusPattern](#module_api..Api+onStatusPattern) ⇒ <code>Api</code>
    * [~api(url, [options])](#module_api..api) ⇒ <code>Api</code>
    * [~HttpResponse](#module_api..HttpResponse)
    * [~statusCallback](#module_api..statusCallback) : <code>function</code>

<a name="module_api..Api"></a>

### api~Api
**Kind**: inner class of [<code>api</code>](#module_api)  

* [~Api](#module_api..Api)
    * [.header](#module_api..Api+header) ⇒ <code>Api</code>
    * [.headers](#module_api..Api+headers) ⇒ <code>Api</code>
    * [.httpOptions](#module_api..Api+httpOptions) ⇒ <code>Api</code>
    * [.response](#module_api..Api+response) ⇒ <code>Promise.&lt;HttpResponse&gt;</code>
    * [.json](#module_api..Api+json) ⇒ <code>Promise.&lt;object&gt;</code>
    * [.get](#module_api..Api+get) ⇒ <code>Api</code>
    * [.post](#module_api..Api+post) ⇒ <code>Api</code>
    * [.put](#module_api..Api+put) ⇒ <code>Api</code>
    * [.patch](#module_api..Api+patch) ⇒ <code>Api</code>
    * [.delete](#module_api..Api+delete) ⇒ <code>Api</code>
    * [.method](#module_api..Api+method) ⇒ <code>Api</code>
    * [.body](#module_api..Api+body) ⇒ <code>Api</code>
    * [.form](#module_api..Api+form) ⇒ <code>Api</code>
    * [.attach](#module_api..Api+attach) ⇒ <code>Api</code>
    * [.onStatusPattern](#module_api..Api+onStatusPattern) ⇒ <code>Api</code>

<a name="module_api..Api+header"></a>

#### api.header ⇒ <code>Api</code>
Adds a HTTP header to the request chain

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object with same options  

| Param | Type | Description |
| --- | --- | --- |
| key | <code>string</code> | key of the header |
| value | <code>string</code> | value of the header |

**Example**  
```js
api('url').header('Authorization', 'Basic JHkasdfjh')
```
<a name="module_api..Api+headers"></a>

#### api.headers ⇒ <code>Api</code>
Adds HTTP header collection to the request chain

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object with same options  

| Param | Type | Description |
| --- | --- | --- |
| headers | <code>object</code> | HTTP headers collection |

**Example**  
```js
api('url').headers({ 'Authorization': 'Basic JHkasdfjh', 'X-Custom-header': true })
```
<a name="module_api..Api+httpOptions"></a>

#### api.httpOptions ⇒ <code>Api</code>
Modifies native Nodejs HTTP request by overriding `options` parameter of `http.request()`

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object with same options  

| Param | Type | Description |
| --- | --- | --- |
| options | <code>object</code> | Options to be set in the native Nodejs HTTP request |

**Example**  
```js
api('url').httpOptions({ 'headers': { 'Authorization': 'Basic JHkasdfjh', 'X-Custom-header': true }})
```
<a name="module_api..Api+response"></a>

#### api.response ⇒ <code>Promise.&lt;HttpResponse&gt;</code>
Invoking the backend endpoint

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Promise.&lt;HttpResponse&gt;</code> - a Javascript promise object containing the response  
**Example**  
```js
await api('url').get('/').response()   // { status: 200, headers: {...}, body: '<success>1</success>', response: {...} }
```
<a name="module_api..Api+json"></a>

#### api.json ⇒ <code>Promise.&lt;object&gt;</code>
Invoking the backend endpoint and returning json parsed response body

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Promise.&lt;object&gt;</code> - a Javascript promise object containing the response parsed to Javascript object  
**Example**  
```js
await api('url').get('/').json()   // { response: 'Works!' }
```
<a name="module_api..Api+get"></a>

#### api.get ⇒ <code>Api</code>
Creates an 'Api' obect for GET requests using resource path provided

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for a GET request  

| Param | Type | Description |
| --- | --- | --- |
| [path] | <code>string</code> | resource path to be suffixed to base URL |

**Example**  
```js
api('url').get('/path')
api('url').get()
```
<a name="module_api..Api+post"></a>

#### api.post ⇒ <code>Api</code>
Creates an 'Api' object for POST requests using resource path provided

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for a POST request  

| Param | Type | Description |
| --- | --- | --- |
| [path] | <code>string</code> | resource path to be suffixed to base URL |

**Example**  
```js
api('url').post('/')
```
<a name="module_api..Api+put"></a>

#### api.put ⇒ <code>Api</code>
Creates an 'Api' object for PUT requests using resource path provided

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for a PUT request  

| Param | Type | Description |
| --- | --- | --- |
| [path] | <code>string</code> | resource path to be suffixed to base URL |

**Example**  
```js
api('url').put('/person/23')
```
<a name="module_api..Api+patch"></a>

#### api.patch ⇒ <code>Api</code>
Creates an 'Api' object for PATCH requests using resource path provided

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for a PATCH request  

| Param | Type | Description |
| --- | --- | --- |
| [path] | <code>string</code> | resource path to be suffixed to base URL |

**Example**  
```js
api('url').patch('/person/23')
```
<a name="module_api..Api+delete"></a>

#### api.delete ⇒ <code>Api</code>
Creates an 'Api' object for DELETE requests using resource path provided

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for a DELETE request  

| Param | Type | Description |
| --- | --- | --- |
| [path] | <code>string</code> | resource path to be suffixed to base URL |

**Example**  
```js
api('url').delete('/person/23')
```
<a name="module_api..Api+method"></a>

#### api.method ⇒ <code>Api</code>
Creates an 'Api' object for given HTTP method with optional ontext path parameters

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for request  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [method] | <code>string</code> | <code>&quot;GET&quot;</code> | HTTP method (GET|POST|PUT|DELETE|PATCH|OPTIONS) |
| [path] | <code>string</code> |  | resource path to be suffixed to base URL |

**Example**  
```js
api('url').method('PATCH', '/item/21')
api('url').method('GET')
```
<a name="module_api..Api+body"></a>

#### api.body ⇒ <code>Api</code>
Creates an 'Api' object for json body request

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for request  

| Param | Type | Description |
| --- | --- | --- |
| data | <code>object</code> \| <code>Array</code> | request payload as a Javascript object or array which will be converted to JSON inside the method |

**Example**  
```js
let payload = { field1: 'foo', field2: 'bar'}
api('url').body(payload)   // sets the request JSON encoded body
                           // { 'field1': 'foo', 'field2': 'bar'}
```
<a name="module_api..Api+form"></a>

#### api.form ⇒ <code>Api</code>
Creates an 'Api' object for form post request with `multipart/form-data` content type

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for request  

| Param | Type | Description |
| --- | --- | --- |
| data | <code>object</code> | a Javascript object which will be converted to form-data where object key being the form post element key and object value being the form post element value |

**Example**  
```js
let payload = { field1: 'foo', field2: 'bar'}
api('url').form(payload)    // sets the request body to have form-data
                            // field1  → foo
                            // field2  → bar
```
<a name="module_api..Api+attach"></a>

#### api.attach ⇒ <code>Api</code>
Creates an 'Api' object for uploading files with a post request with `multipart/form-data` content type

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for request  

| Param | Type | Description |
| --- | --- | --- |
| fileBuffer | <code>Buffer</code> | file content which need to be upload |
| filename | <code>String</code> | name that need to be given for the file |

**Example**  
```js
let fileBuffer = fs.readFileSync('./resources/test.pdf')  // Read the source file as a buffer
api('url').attach(fileBuffer, 'coco')  // sets the request body to upload the file
                            // file content  → fileBuffer
                            // file Name  → coco
```
<a name="module_api..Api+onStatusPattern"></a>

#### api.onStatusPattern ⇒ <code>Api</code>
Registers a callback function for HTTP status code regex pattern. There can be multiple callback functions
registered for a request chain.

**Kind**: instance property of [<code>Api</code>](#module_api..Api)  
**Returns**: <code>Api</code> - new instance of `Api` object for a POST request  

| Param | Type | Description |
| --- | --- | --- |
| statusRegex | <code>string</code> | regex pattern to match the response status code |
| cb | <code>statusCallback</code> | callback function to be executed when matching status code is recieved |

**Example**  
```js
api('url').onStatusPattern('401', (response) => { console.error(response) })    // callback on status 401
api('url').onStatusPattern('20[0|1]', (response) => { console.log(response) })  // callback on status matching pattern 200 or 201
```
<a name="module_api..api"></a>

### api~api(url, [options]) ⇒ <code>Api</code>
Create a API call chin builder instance

**Kind**: inner method of [<code>api</code>](#module_api)  
**Returns**: <code>Api</code> - new instance of `Api` object  

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| url | <code>string</code> |  | base URL of the request builder |
| [options] | <code>object</code> |  | optional configurations for the request chain |
| [options.baseUrl] | <code>string</code> |  | base url of the request chain |
| [options.method] | <code>string</code> | <code>&quot;GET&quot;</code> | HTTP method of the request chain |
| [options.headers] | <code>object</code> |  | HTTP headers of the request chain |

**Example**  
```js
api('url')           // new Api('url')
api('url', options)  // new Api('url', options)
```
<a name="module_api..HttpResponse"></a>

### api~HttpResponse
**Kind**: inner typedef of [<code>api</code>](#module_api)  
**Properties**

| Name | Type | Description |
| --- | --- | --- |
| status | <code>number</code> | HTTP response status code |
| headers | <code>object</code> | response headers object |
| body | <code>string</code> | response body as a raw string |
| response | <code>object</code> | original response from the native HTTP request |

<a name="module_api..statusCallback"></a>

### api~statusCallback : <code>function</code>
Callback function for the status matching

**Kind**: inner typedef of [<code>api</code>](#module_api)  

| Param | Type | Description |
| --- | --- | --- |
| res | <code>object</code> | response object called with successful callback invocation |
| res.status | <code>number</code> | HTTP response status code |
| res.headers | <code>object</code> | response headers object |
| res.body | <code>string</code> | response body as a raw string |
| res.response | <code>string</code> | original response from the native HTTP request |


_This is an auto generated file. Please don't make changes manually_