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
:
// orconst httpClient = httpClient const myClient = myClient
You may also supply base configuration for re-usability when defining your client:
const myConfiguredClient = // you can add more options based on a previous client - without affecting the old onelet moreHeadersClient = myConfiguredClient// Or for this case you can just write:moreHeadersClient = myConfiguredClient myConfiguredClient // appends '/get' to the baseUrl set above ('withUrl(..)') // sets query: ?key=value&foo=bar // Accept header = application/json // execute GET request asynchronously // transforms the body to a JS object // do something with the body/data // or, get body as a string:myConfiguredClient // POST with body:const myBody = someProperty: 'value' myConfiguredClient // With Blobs:myConfiguredClient // Query parametersmyConfiguredClient // adds a single query-param foo=bar. // To add multiple key-value pairs and overwrite previously set queries (last param = true; default false): // result: ?key=value&anotherKey=anotherValue // 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 = // Or maybe a post-request function to log responsesconst responseLogClient = myClient
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 = // 5 seconds // retry 5 times or until status === 200 myClient = myClient
Common HTTP models
http-toolkit comes with commonly used HTTP codes, methods, media-types, and headers:
ObjectObject const jsonType = MediaTypeJSONconst forwardedHeader = HttpHeaderX_FORWARDED_FOR