@feizheng/next-apply-fetch-middleware
v1.0.0
Published
Fetch meet middlewares.
Downloads
14
Readme
next-apply-fetch-middleware
Fetch meet middlewares.
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.