1.0.0-0 • Published 1 year ago

@novigi/api v1.0.0-0

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

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

ParamTypeDescription
keystringkey of the header
valuestringvalue 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

ParamTypeDescription
headersobjectHTTP 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

ParamTypeDescription
optionsobjectOptions 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

ParamTypeDescription
pathstringresource 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

ParamTypeDescription
pathstringresource 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

ParamTypeDescription
pathstringresource 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

ParamTypeDescription
pathstringresource 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

ParamTypeDescription
pathstringresource 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

ParamTypeDefaultDescription
methodstring"GET"HTTP method (GETPOSTPUTDELETEPATCHOPTIONS)
pathstringresource 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

ParamTypeDescription
dataobject | Arrayrequest 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

ParamTypeDescription
dataobjecta 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

ParamTypeDescription
fileBufferBufferfile content which need to be upload
filenameStringname 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

ParamTypeDescription
statusRegexstringregex pattern to match the response status code
cbstatusCallbackcallback 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

ParamTypeDefaultDescription
urlstringbase URL of the request builder
optionsobjectoptional configurations for the request chain
options.baseUrlstringbase url of the request chain
options.methodstring"GET"HTTP method of the request chain
options.headersobjectHTTP 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

NameTypeDescription
statusnumberHTTP response status code
headersobjectresponse headers object
bodystringresponse body as a raw string
responseobjectoriginal response from the native HTTP request

api~statusCallback : function

Callback function for the status matching

Kind: inner typedef of api

ParamTypeDescription
resobjectresponse object called with successful callback invocation
res.statusnumberHTTP response status code
res.headersobjectresponse headers object
res.bodystringresponse body as a raw string
res.responsestringoriginal response from the native HTTP request

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