npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

http-toolkit

v2.0.1

Published

Well-documented toolkit for making elegant HTTP requests with JavaScript

Downloads

69

Readme

Http Toolkit for Node.js

npm npm Build Status Coverage Status CodeFactor

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