@feizheng/next-apply-fetch-middleware

1.0.0 • Public • Published

next-apply-fetch-middleware

Fetch meet middlewares.

version license size download

installation

npm install -S @feizheng/next-apply-fetch-middleware

usage

import '@feizheng/next-apply-fetch-middleware';

const midJson = function (inFetch) {
  return function (url, options) {
    return inFetch(url, options).then(res => res.json());
  }
};

const midTimeout = function (inFetch) {
  return function (url, inOptions) {
    const controller = new AbortController();
    const options = Object.assign({ signal: controller.signal, timeout: 3 * 1000 }, inOptions);
    const timer = setTimeout(() => {
      controller.abort();
    }, options.timeout);

    return new Promise((resolve, reject) => {
      inFetch(url, options).then(res => {
        clearTimeout(timer);
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  }
};


const betterFetch = nx.applyFetchMiddleware([
  midJson,
  midTimeout
])(fetch);


// 1. return json
// 2. has timeout
betterFetch('https://api.github.com/users/afeiship', { timeout: 3 * 1000 }).then(res => {
  console.log(res);
});

license

Code released under the MIT license.

/@feizheng/next-apply-fetch-middleware/

    Package Sidebar

    Install

    npm i @feizheng/next-apply-fetch-middleware

    Weekly Downloads

    1

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    6.71 kB

    Total Files

    6

    Last publish

    Collaborators

    • afeiship