Http Toolkit for Node.js
http-toolkit provides utilities and tools to allow more elegant HTTP communication.
Its goals are to:
- provide clean, simple and elegant functionality for communication across http
- provide appropriate documentation, tied directly to the code for maximum IDE-support (development just goes quicker when you don't have to constantly search the web to explain some function)
- offer simple out-of-the-box JavaScript compatibility
Installation and usage
npm install http-toolkit
or yarn install http-toolkit
Then import as any other package.
Example usage of the httpClient
:
import { httpClient } from 'http-toolkit'
const httpClient = require('http-toolkit').httpClient
const myClient = httpClient()
myClient.getAsync('https://httpbin.org/get').bodyToJson().then(data => console.log(data))
You may also supply base configuration for re-usability when defining your client:
import { httpClient, HttpHeader, MediaType } from 'http-toolkit'
const myConfiguredClient = httpClient()
.withUrl('https://httpbin.org')
.withHeader('apikey', 'my-api-key')
.withCors()
.withAuth('Basic user:password')
let moreHeadersClient = myConfiguredClient.withHeader(HttpHeader.CONTENT_TYPE, MediaType.JSON)
moreHeadersClient = myConfiguredClient.withContentType(MediaType.JSON)
myConfiguredClient
.withPath('/get')
.addQueries({key: 'value', foo: 'bar'})
.acceptJson()
.getAsync()
.bodyToJson()
.then(data => console.log(data))
myConfiguredClient
.getAsync('/get')
.bodyToString()
.then(data => console.log(data))
const myBody = { someProperty: 'value' }
myConfiguredClient
.withBody(myBody)
.postAsync('/post')
.catch(e => console.log('maybe something went wrong?', e))
myConfiguredClient
.getAsync('/bytes/100')
.bodyToBlob()
.then(blob => console.log(`do something with your ${blob}`))
myConfiguredClient
.addQuery('foo', 'bar')
.addQueries({key: 'value', anotherKey: 'anotherValue'}, true)
.withQuery('foo=bar')
Pre- and postfetch
You can add pre- and post-flight functions to be run before or after every request. For example if you want to log all requests.
Note; be careful not to use the stream in the postfetch (prefer to use clone)
const myClient = httpClient()
.withUrl('https://httpbin.org')
.addPrefetch((url, options) => console.log(`sending a ${options.method}-request, body is ${options.body}`))
const responseLogClient = myClient.addPostfetch(
(url, options, response) => {
response.clone()
.json()
.then(clonedJson => console.log(`response is ${clonedJson}`))
})
In the above example; anyone who uses myClient, will automatically get a log for their requests. Anyone who uses responseLogClient will get the postfetch log of the response, as well as the prefetch log from myClient (since it was based off of it).
Timeout and retries
The client can also be configured with a specific timeout that will abort requests taking too long.
Another feature is number of retries and retryWhen that will reject any request that doesn't fulfill a certain check. This can be powerfully configured to check if the body contains what you need - else try fetching it again.
myClient = httpClient({url: 'https://httpbin.org/get'})
.withTimeout(5000)
.withRetries(5)
.retryWhen(response => !isResponseStatus(response, 200))
myClient = myClient.retryWhen(
async response => await response.clone.json().then(data => data.key === 'myValue')
)
Common HTTP models
http-toolkit comes with commonly used HTTP codes, methods, media-types, and headers:
import { HttpMethods, HttpStatus, MediaType, HttpHeader } from 'http-toolkit'
Object.keys(HttpMethods).map(key => console.log(HttpMethods[key]))
Object.values(HttpStatus).map(status => console.log(`code: ${status.code}, msg: ${status.message}`))
const jsonType = MediaType.JSON
const forwardedHeader = HttpHeader.X_FORWARDED_FOR