http-toolkit
v2.0.1
Published
Well-documented toolkit for making elegant HTTP requests with JavaScript
Downloads
69
Maintainers
Readme
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'
// or
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')
// you can add more options based on a previous client - without affecting the old one
let moreHeadersClient = myConfiguredClient.withHeader(HttpHeader.CONTENT_TYPE, MediaType.JSON)
// Or for this case you can just write:
moreHeadersClient = myConfiguredClient.withContentType(MediaType.JSON)
myConfiguredClient
.withPath('/get') // appends '/get' to the baseUrl set above ('withUrl(..)')
.addQueries({key: 'value', foo: 'bar'}) // sets query: ?key=value&foo=bar
.acceptJson() // Accept header = application/json
.getAsync() // execute GET request asynchronously
.bodyToJson() // transforms the body to a JS object
.then(data => console.log(data)) // do something with the body/data
// or, get body as a string:
myConfiguredClient
.getAsync('/get')
.bodyToString()
.then(data => console.log(data))
// POST with body:
const myBody = { someProperty: 'value' }
myConfiguredClient
.withBody(myBody)
.postAsync('/post')
.catch(e => console.log('maybe something went wrong?', e))
// With Blobs:
myConfiguredClient
.getAsync('/bytes/100')
.bodyToBlob()
.then(blob => console.log(`do something with your ${blob}`))
// Query parameters
myConfiguredClient
.addQuery('foo', 'bar') // adds a single query-param foo=bar.
// To add multiple key-value pairs and overwrite previously set queries (last param = true; default false):
.addQueries({key: 'value', anotherKey: 'anotherValue'}, true) // result: ?key=value&anotherKey=anotherValue
.withQuery('foo=bar') // manually set (overwrite) query by specifying your own. Leading '?' is added if omitted
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}`))
// Or maybe a post-request function to log responses
const responseLogClient = myClient.addPostfetch(
(url, options, response) => {
response.clone() // Use clone() so we don't use the response-stream
.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) // 5 seconds
.withRetries(5)
.retryWhen(response => !isResponseStatus(response, 200)) // retry 5 times or until status === 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