Mohammed Manssour

Tags:JS
fetch HTTP wrapper npm package

A simple, Intuitive and expressive http client built on top of fetch

✅ It's lightweight and depends on fetch 😍

👌 It has an intuitive and expressive api 🎉

👊 It depends on middleware pattern to extends functionality.

✅ It was built with and supports TypeScript 💪

😅 It still in beta

Why Bother?

for me axios is a very powerful package to make different kinds of http requests. but, when it's used a lot the code turns to be messy because of the options object. So I build this package to provide an elegant, expressive and intuitive wrapper around fetch to keep code simple and organized when working with http apis.

Installation

all what you have to do is run the following command

npm i fetch-http-wrapper

Usage

You can instantiate new request by using the request method or any of other related methods.All of the following methods will return an instance of the class FetchRequest

  • Instantiate request with {method} and {url}
const request = Fetch.request(method, url);
  • Instantiate get request with {url};
const request = Fetch.get(url);
  • instantiate post request with {url}
const request = Fetch.post(url);
  • instantiate put request with {url}
const request = Fetch.put(url);
  • instantiate patch request with {url}
const request = Fetch.patch(url);
  • instantiate head request with {url}
const request = Fetch.head(url);
  • instantiate delete request with {url}
const request = Fetch.delete(url);

The FetchRequest class has the following methods to help you build the request. All of the following methods will return the instance.

  • add query params to the url
request.withParams({
    key: 'value',
    key2: 'value2'
})
  • add a single parameter to the query list to be added to the url
request.param('key': 'value');
  • add request headers
request.withHeaders({
    'Content-Type': 'application/json'
})
  • add a single header to the headers list
request.header('Content-Type': 'application/json');
  • add request body
request.withBody({
    key: 'value',
})
  • add a single item body item to the body
request.withBodyItem('key', 'value')
  • specify request credentials: Contains the credentials of the request (e.g., "omit", "same-origin", "include"). The default is "same-origin".
request.credentials('omit')
  • specify request mode: Contains the mode of the request (e.g., cors, no-cors, same-origin, navigate.)
request.mode('cors')
  • specify request cache: Contains the cache mode of the request
request.cache('no-cache');
  • specify request redirect policy: Contains the mode for how redirects are handled. It may be one of follow, error, or manual
request.redirect('follow');
  • specify request referrer: Contains the referrer of the request
request.referrer('');
  • specify request integrity: Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
request.integrity('')
  • to keep the code elegant when adding conditions use when method to customize the request
request.when(true, (req: FetchRequest) => req.param('parent', parent))

sending request

use call method to send http request after being configured, It returns a promise.

request.call()
    .then(response => {})

Example usage

Fetch.get('http://mohammedmanssour.me')
    .withHeaders({
        'Authorization' : '{token}'
    })
    .withParams({
        key: 'value'
    })
    .mode('no-cors')
    .call()
    .then(response => {});

Middlewares

Building Before middlewares

before middlewares is used to manipulate request config before sending the http request. to add a before middleware toFetch.before()method and make sure to return options.

use options.clone() to get a new cloned object of the original options

Fetch.before(options => {
    const newOptions = options.clone();
    // do your thing here
    return newOptions;
})

the option paramaeter is an instance of FetchOptions class that has the following attributes

    url: string;
    method: string;
    headers: { [key: string]: string } = {};
    mode?: string;
    body?: any = {};
    query?: QueryObject = {};
    credentials?: string;
    cache?: string;
    redirect?: string;
    referrer?: string;
    integrity?: string;

before middleware example

in the following example we will use a middleware to add a base url to the provided path by the request

Fetch.before(options => {
    const newOptions = options.clone();
    newOptions.url = `http://mohammedmanssour.me/api/${newOptions.url}`
    return newOptions;
})

Building After middleware

After middleware is used to manipulate the response when the call is done, use Fetch.after() to add an after middleware. It doesn't matter what you return from your after middlewares but make sure to wrap it in a Promise and keep it consistent.

After middlewares takes two arguments:

  1. request: the request that was sent.
  2. response: the request response, an instance of Fetch Response
Fetch.after(
    (request, response) =>
        response.json()
        .then(data => Promise.resolve(data))

Available Middlewares

You can reach the available middlewares by using the Fetch.middlewares property

  • json() it's a before middleware used to add the right headers to the request and to stringify body.
  • jsonResponse() it's an after middleware used to convert the response to json response and returns a promise that has the data and the response.
return Promise.resolve({data, response});
  • query() it's an before middleware used to convert the options query params from an object to a string
Fetch
.before(Fetch.middlewares.query)
.get('http://mohammedmanssour.me')
.withParams({
    key: 'value',
    key2: 'value2'
})

//will become
'http://mohammedmanssour.me?key=value&key2=value'