1.4.1 • Published 2 years ago
retry-my-fetch v1.4.1
retry-my-fetch
It's a decorator for Fetch
API (fetch, isomorphic-fetch, cross-fetch, etc.) which allows resending (retrying) your requests in case if that fails.
npm package
npm i retry-my-fetch
Quick start
Simple retry
import retryMyFetch from 'retry-my-fetch';
const config = {
maxTryCount: 5,
};
const fetchWithRetry = retryMyFetch(fetch, config);
fetchWithRetry('/').then(console.log);
Retry with timeout
import retryMyFetch from 'retry-my-fetch';
const config = {
timeout: 3000, // it should call next retry after 3 sec
maxTryCount: 5,
};
const fetchWithRetry = retryMyFetch(fetch, config);
fetchWithRetry('/').then(console.log);
Update JWT token and retry
import retryMyFetch from 'retry-my-fetch';
const config = {
beforeRefetch: async (url, fetchOptions, statusCode, retryConter) => {
// do something, i.e. refresh JWT token
const newAccessToken = await getToken(); // some async function
// update fetch options
const newFetchOptions = {
...fetchOptions,
headers: new Headers({
Authorization: `Bearer ${newAccessToken}`,
}),
};
// return new options in order to retry call with new options
return newFetchOptions;
},
maxTryCount: 5,
};
const fetchWithRetry = retryMyFetch(fetch, config);
const options = {
headers: new Headers({
Authorization: `Bearer ${someOldToken}`,
}),
};
fetchWithRetry('/', options).then(console.log);
Use AbortController
The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.
import retryMyFetch from 'retry-my-fetch';
const beforeRefetch = async (url, fetchOptions, statusCode, retryConter, isRejected) => {
const token = getCurrentToken();
if (!isRejected) {
// refresh JWT token
const freshAccessToken = await getToken(); // some async function
}
// update and return new options in order to retry call with new options
return {
...fetchOptions,
headers: new Headers({
Authorization: `Bearer ${isRejected ? token : freshAccessToken}`,
}),
};
};
// prepare configuration
const config = {
useAbortController: true,
beforeRefetch,
maxTryCount: 5,
};
// get decorated fetch
const fetchWithRetry = retryMyFetch(fetch, config);
const options = {
headers: new Headers({
Authorization: `Bearer ${someOldToken}`,
}),
};
// do request with decorated fetch
fetchWithRetry('/', options).then(console.log);
See src/interfaces.ts
for further details.
Do not retry if statuses
import retryMyFetch from 'retry-my-fetch';
const config = {
doNotRetryIfStatuses: [400], // number[]
};
const fetchWithRetry = retryMyFetch(fetch, config);
fetchWithRetry('/').then(console.log);
1.4.1
2 years ago
1.4.0
3 years ago
1.3.0
3 years ago
1.2.3-beta.3
3 years ago
1.2.0
3 years ago
1.2.3-beta.1
3 years ago
1.2.3-beta.2
3 years ago
1.2.2
3 years ago
1.2.1
3 years ago
1.2.0-beta.1
3 years ago
1.1.0
3 years ago
1.0.0
3 years ago