hwf

http-with-fetch

A tiny abstraction over fetch

Showing:

Popularity

Downloads/wk

0

GitHub Stars

3

Maintenance

Last Commit

1yr ago

Contributors

3

Package

Dependencies

0

License

MIT

Type Definitions

Tree-Shakeable

Yes?

Categories

Readme

http-with-fetch

A tiny (< 1 kb) abstraction over building complex wrappers over the fetch API.

Description

http-with-fetch provides an easier way to write APIs using fetch.

Installation

npm i http-with-fetch

Usage

Intended to be used as a ES6 module ( import ) or using require.

import { HTTP } from 'http-with-fetch'
let userService = new HTTP('/users')

Motivation

Consider the following code

let options = { mode: 'cors' }

fetch('/resource/point1', options)

fetch('/resource/point2', options)

fetch('/resource/point3', options)
  
fetch('/resource/point4', options)

If you were to do a POST at /resource/point3, then you can't reuse options in the fetch call and the code would then become

let options = { mode: 'cors' }

let data = { 'some': 'data' }

fetch('/resource/point1', options)

fetch('/resource/point2', options)

fetch('/resource/point3', {
  mode: 'cors',
  method: 'POST',
  headers: {
    'content-type': 'application/json'
  }
  body: JSON.stringify(data)
})
  
fetch('/resource/point4', options)

This problem increases when each fetch does some common things and also its own specific stuff.

With http-with-fetch it can be rewritten as,

const { HTTP } = require('http-with-fetch')

let http = new HTTP('/resource/')

const data = { 'some': 'data' }

http.use(http.add('mode', 'cors'))

http.get('point1')

http.get('point2')

http.method('point3', "POST",
  http.add('body', JSON.stringify(data)),
  http.add('headers', {'content-type': 'application/json'})
)

http.get('point4')

API

HTTP(base?: string)

Creates a new object.

ArgumentsDescription
baseThe base url of the resource. Default is ""

add(key: string, value: string | Record<string, string>)

Helper method to create interceptors.

use(interceptor: function)

Adds an common interceptor. All requests will be intercepted by this.

method(url: string, method: string, ...interceptors?: function[])

Make a request.

ArgumentsDescription
urlThe url of the resource (relative to the base URL)
methodHTTP method to use. Uppercase only.
interceptorsInterceptors specific to this request.

get(url: string, ...interceptors?: function[])

An alias for method with verb=GET

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial