@jswork/next-apply-fetch-middleware
v1.0.10
Published
Fetch meet middlewares.
Downloads
260
Maintainers
Readme
next-apply-fetch-middleware
Fetch meet middlewares.
installation
npm install -S @jswork/next-apply-fetch-middleware
usage
import '@jswork/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
])(window.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.