GithubHelp home page GithubHelp logo

http-client's Introduction

http-client Travis npm package

http-client lets you compose HTTP clients using JavaScript's fetch API. This library has the following goals:

  • Preserve the full capabilities of the fetch API
  • Provide an extendable middleware API
  • Use the same API on both client and server

Installation

Using npm:

$ npm install --save http-client

http-client requires you to bring your own global fetch function. isomorphic-fetch is a great polyfill.

Then, use as you would anything else:

// using ES6 modules
import { fetch, createFetch } from 'http-client'

// using CommonJS modules
var fetch = require('http-client').fetch
var createFetch = require('http-client').createFetch

The UMD build is also available on npmcdn:

<script src="https://npmcdn.com/http-client/umd/http-client.min.js"></script>

You can find the library on window.HTTPClient.

Usage

http-client simplifies the process of creating flexible HTTP clients that work in both node and the browser. You create your own fetch function using the createFetch method, optionally passing middleware as arguments.

import { createFetch, base, accept, parseJSON } from 'http-client'

const fetch = createFetch(
  base('https://api.stripe.com/v1'),  // Prefix all request URLs
  accept('application/json'),         // Set "Accept: application/json" in the request headers
  parseJSON()                         // Read the response as JSON and put it in response.jsonData
)

fetch('/customers/5').then(response => {
  console.log(response.jsonData)
})

http-client also exports a base fetch function if you need it (i.e. don't want middleware).

Using Callbacks

Arrrgggh, but I HATE promises!!

It's cool. I've got your back.

All fetch functions in http-client are enhanced with a trailing callback argument that you can use to handle responses and/or errors just like you're used to doing in node.js.

fetch('/customers/5', (error, response) => {
  // ...
})

Notice I said the callback is the trailing argument. This means that you can omit either of the first two arguments; just make sure the callback comes last.

Note: When you do use a callback, a promise is still returned. However, it always resolves to undefined. It is assumed that if you're using a callback you'll do anything you need to with the response and/or error in the callback.

Top-level API

fetch([input], [options], [callback])

An enhanced fetch function that accepts an optional callback as a trailing argument. Use this directly if you don't need any middleware.

createFetch(...middleware)

Creates a fetch function that is fronted by some middleware. This function has the same signature as the enhanced fetch function in the top-level API.

createStack(...middleware)

Combines several middleware into one, in the same order they are provided as arguments. Use this function to create re-usable middleware stacks.

handleResponse(callback)

A helper for creating middleware that enhances the response object in some way. Used internally to create the parseText and parseJSON middleware.

Middleware

http-client provides a variety of middleware that may be used to extend the functionality of the client. Out of the box, http-client ships with the following middleware:

method(verb)

Sets the request method.

import { createFetch, method } from 'http-client'

const fetch = createFetch(
  method('POST')
)

header(name, value)

Adds a header to the request.

import { createFetch, header } from 'http-client'

const fetch = createFetch(
  header('Content-Type', 'application/json')
)

auth(value)

Adds an Authorization header to the request.

import { createFetch, auth } from 'http-client'

const fetch = createFetch(
  auth('Bearer ' + oauth2Token)
)

accept(contentType)

Adds an Accept header to the request.

import { createFetch, accept } from 'http-client'

const fetch = createFetch(
  accept('application/json')
)

base(baseURL)

Adds the given baseURL to the beginning of the request URL.

import { createFetch, base } from 'http-client'

const fetch = createFetch(
  base('https://api.stripe.com/v1')
)

fetch('/customers/5') // GET https://api.stripe.com/v1/customers/5

query(object)

Adds the data in the given object (or string) to the query string of the request URL.

body(content, contentType)

Sets the given content string as the request body.

import { createFetch, body } from 'http-client'

const fetch = createFetch(
  body(JSON.stringify(data), 'application/json')
)

json(object)

Adds the data in the given object as JSON to the request body.

params(object)

Adds the given object to the query string of GET/HEAD requests and as a x-www-form-urlencoded payload on all others.

import { createFetch, method, params } from 'http-client'

// Create a client that will append hello=world to the URL in the query string
const fetch = createFetch(
  params({ hello: 'world' })
)

// Create a client that will send hello=world as POST data
const fetch = createFetch(
  method('POST'),
  params({ hello: 'world' })
)

parseText(propertyName = 'textString')

Reads the response body as text and puts it on response.textString.

import { createFetch, parseText } from 'http-client'

const fetch = createFetch(
  parseText()
)

fetch(input).then(response => {
  console.log(response.textString)
})

parseJSON(propertyName = 'jsonData')

Reads the response body as JSON and puts it on response.jsonData.

import { createFetch, parseJSON } from 'http-client'

const fetch = createFetch(
  parseJSON()
)

fetch(input).then(response => {
  console.log(response.jsonData)
})

requestInfo()

Adds requestURL and requestOptions properties to the response (or error) object so you can inspect them. Mainly useful for testing/debugging (should be put last in the list of middleware).

import { createFetch, requestInfo } from 'http-client'

const fetch = createFetch(
  // ...
  requestInfo()
)

fetch(input).then(response => {
  console.log(response.requestURL, response.requestOptions)
})

Stacks

Middleware may be combined together into re-usable middleware "stacks" using createStack. A stack is itself a middleware that is composed of one or more other pieces of middleware.

This is useful when you have a common set of functionality that you'd like to share between several different fetch methods, e.g.:

import { createStack, createFetch, header, base, parseJSON } from 'http-client'

const commonStack = createStack(
  header('X-Auth-Key', key),
  header('X-Auth-Email', email),
  base('https://api.cloudflare.com/client/v4'),
  parseJSON()
)

// This fetch function can be used standalone...
const fetch = createFetch(commonStack)

// ...or we can add further middleware to create another fetch function!
const fetchSinceBeginningOf2015 = createFetch(
  commonStack,
  query({ since: '2015-01-01T00:00:00Z' })
)

http-client's People

Contributors

emmenko avatar mjackson avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.