@novigi/api

1.0.0-0Β β€’Β PublicΒ β€’Β Published

npm (scoped) NPM Statements Branches Functions Lines

@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
  1. Import the library
const lib = require('@novigi/api');

πŸ“– Documentation

api

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

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~Api

Kind: inner class of api

api.header β‡’ Api

Adds a HTTP header to the request chain

Kind: instance property of Api
Returns: Api - new instance of Api object with same options

Param Type Description
key string key of the header
value string value of the header

Example

api('url').header('Authorization', 'Basic JHkasdfjh')

api.headers β‡’ Api

Adds HTTP header collection to the request chain

Kind: instance property of Api
Returns: Api - new instance of Api object with same options

Param Type Description
headers object HTTP headers collection

Example

api('url').headers({ 'Authorization': 'Basic JHkasdfjh', 'X-Custom-header': true })

api.httpOptions β‡’ Api

Modifies native Nodejs HTTP request by overriding options parameter of http.request()

Kind: instance property of Api
Returns: Api - new instance of Api object with same options

Param Type Description
options object Options to be set in the native Nodejs HTTP request

Example

api('url').httpOptions({ 'headers': { 'Authorization': 'Basic JHkasdfjh', 'X-Custom-header': true }})

api.response β‡’ Promise.<HttpResponse>

Invoking the backend endpoint

Kind: instance property of Api
Returns: Promise.<HttpResponse> - a Javascript promise object containing the response
Example

await api('url').get('/').response()   // { status: 200, headers: {...}, body: '<success>1</success>', response: {...} }

api.json β‡’ Promise.<object>

Invoking the backend endpoint and returning json parsed response body

Kind: instance property of Api
Returns: Promise.<object> - a Javascript promise object containing the response parsed to Javascript object
Example

await api('url').get('/').json()   // { response: 'Works!' }

api.get β‡’ Api

Creates an 'Api' obect for GET requests using resource path provided

Kind: instance property of Api
Returns: Api - new instance of Api object for a GET request

Param Type Description
[path] string resource path to be suffixed to base URL

Example

api('url').get('/path')
api('url').get()

api.post β‡’ Api

Creates an 'Api' object for POST requests using resource path provided

Kind: instance property of Api
Returns: Api - new instance of Api object for a POST request

Param Type Description
[path] string resource path to be suffixed to base URL

Example

api('url').post('/')

api.put β‡’ Api

Creates an 'Api' object for PUT requests using resource path provided

Kind: instance property of Api
Returns: Api - new instance of Api object for a PUT request

Param Type Description
[path] string resource path to be suffixed to base URL

Example

api('url').put('/person/23')

api.patch β‡’ Api

Creates an 'Api' object for PATCH requests using resource path provided

Kind: instance property of Api
Returns: Api - new instance of Api object for a PATCH request

Param Type Description
[path] string resource path to be suffixed to base URL

Example

api('url').patch('/person/23')

api.delete β‡’ Api

Creates an 'Api' object for DELETE requests using resource path provided

Kind: instance property of Api
Returns: Api - new instance of Api object for a DELETE request

Param Type Description
[path] string resource path to be suffixed to base URL

Example

api('url').delete('/person/23')

api.method β‡’ Api

Creates an 'Api' object for given HTTP method with optional ontext path parameters

Kind: instance property of Api
Returns: Api - new instance of Api object for request

Param Type Default Description
[method] string "GET" HTTP method (GET
[path] string resource path to be suffixed to base URL

Example

api('url').method('PATCH', '/item/21')
api('url').method('GET')

api.body β‡’ Api

Creates an 'Api' object for json body request

Kind: instance property of Api
Returns: Api - new instance of Api object for request

Param Type Description
data object | Array request payload as a Javascript object or array which will be converted to JSON inside the method

Example

let payload = { field1: 'foo', field2: 'bar'}
api('url').body(payload)   // sets the request JSON encoded body
                           // { 'field1': 'foo', 'field2': 'bar'}

api.form β‡’ Api

Creates an 'Api' object for form post request with multipart/form-data content type

Kind: instance property of Api
Returns: Api - new instance of Api object for request

Param Type Description
data object 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

let payload = { field1: 'foo', field2: 'bar'}
api('url').form(payload)    // sets the request body to have form-data
                            // field1  β†’ foo
                            // field2  β†’ bar

api.attach β‡’ Api

Creates an 'Api' object for uploading files with a post request with multipart/form-data content type

Kind: instance property of Api
Returns: Api - new instance of Api object for request

Param Type Description
fileBuffer Buffer file content which need to be upload
filename String name that need to be given for the file

Example

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

api.onStatusPattern β‡’ Api

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 Api
Returns: Api - new instance of Api object for a POST request

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

Example

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

api~api(url, [options]) β‡’ Api

Create a API call chin builder instance

Kind: inner method of api
Returns: Api - new instance of Api object

Param Type Default Description
url string base URL of the request builder
[options] object optional configurations for the request chain
[options.baseUrl] string base url of the request chain
[options.method] string "GET" HTTP method of the request chain
[options.headers] object HTTP headers of the request chain

Example

api('url')           // new Api('url')
api('url', options)  // new Api('url', options)

api~HttpResponse

Kind: inner typedef of api
Properties

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

api~statusCallback : function

Callback function for the status matching

Kind: inner typedef of api

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

This is an auto generated file. Please don't make changes manually

Readme

Keywords

none

Package Sidebar

Install

npm i @novigi/api

Weekly Downloads

3

Version

1.0.0-0

License

MIT

Unpacked Size

32.7 kB

Total Files

4

Last publish

Collaborators

  • buddhima
  • nov_user
  • madushak