Skip to content

Create your own fetch with composable request middleware.

License

Notifications You must be signed in to change notification settings

eliashussary/fetch-with

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fetch-with

Create your own fetch with composable request middleware.

Usage

yarn add fetch-with
# or
npm i fetch-with

Example

import {
  fetchWith,
  composeFetchMiddleware,
  FetchWithMiddleware,
} from 'fetch-with';

type FetchJsonBody = { body: object | string };

const withJsonBody: FetchWithMiddleware<FetchJsonBody> = ctx => {
  let body = ctx.options.body;
  if (typeof body === 'object') {
    ctx.options.body = JSON.stringify(body, null, '');
  }

  return ctx;
};

type FetchQuery = { query: object };

const withQuery: FetchWithMiddleware<FetchQuery> = ctx => {
  let query = ctx.options.query;
  if (query) {
    ctx.url += `?${qs.stringify(query)}`;
  }
  return ctx;
};

type FetchOptions = JSONBody & FetchQuery;

const myMiddleware = composeFetchMiddleware<FetchOptions>(
  withJsonBody,
  withQuery
);

const myFetch = (url: string, options: FetchOptions) => {
  return fetchWith(url, options, myMiddleware);
};

myFetch('/api/foo', {
  method: 'post',
  body: {
    foo: 'bar',
  },
});

myFetch('/api/bar', {
  query: {
    offset: 0,
    limit: 30,
  },
});

About

Create your own fetch with composable request middleware.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published