fetch-with
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

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,
  },
});

Readme

Keywords

none

Package Sidebar

Install

npm i fetch-with

Weekly Downloads

1

Version

0.1.0

License

MIT

Unpacked Size

13.3 kB

Total Files

14

Last publish

Collaborators

  • eliashussary