Skip to content

Commit

Permalink
feat: support error retry plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
suhaotian committed Feb 24, 2024
1 parent 43884cd commit b079b42
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 9 deletions.
4 changes: 0 additions & 4 deletions src/plugins/cache.ts

This file was deleted.

71 changes: 68 additions & 3 deletions src/plugins/error-retry.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,69 @@
// TODO
export default function xiorErrorRetryPlugin(options?: object) {
//
import { sleep } from './utils';
import { XiorPlugin } from '../types';
import { XiorError } from '../utils';

export type ErrorRetryOptions = {
/** retry times, default: 0 */
retryTimes?: number;
/**
* Retry after milliseconds, default: 3000
* after first time error retry have interval
*/
retryInterval?: number;
/**
* default: true,
* it's useful because we don't want retry when the error because of token expired
*/
shouldRetryOnError?: (error: XiorError) => boolean;
};

/** @ts-ignore */
declare module 'xior' {
interface XiorRequestConfig extends Omit<ErrorRetryOptions, 'shouldRetryOnError'> {}
}

export default function xiorErrorRetryPlugin(options: ErrorRetryOptions = {}): XiorPlugin {
const {
retryTimes: _retryTimes,
retryInterval: _retryInterval,
shouldRetryOnError,
} = options || {
retryTimes: 0,
retryInterval: 3000,
};

return function (adapter) {
return async (config) => {
const { retryTimes = _retryTimes, retryInterval = _retryInterval } =
config as ErrorRetryOptions;

let timeUp = false;
let count = 0;

async function handleRequest() {
try {
return await adapter(config);
} catch (error) {
if (error instanceof XiorError) {
const shouldRetry = shouldRetryOnError ? shouldRetryOnError(error) : true;
timeUp = retryTimes === count;
if (timeUp || !shouldRetry) {
throw error;
}

if (retryInterval && retryInterval > 0 && count > 0) {
await sleep(retryInterval);
}

count++;
return handleRequest();
}

throw error;
}
}

return handleRequest();
};
};
}
10 changes: 8 additions & 2 deletions src/plugins/repeat-requests-filter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { XiorPlugin } from '../types';

// TODO
export default function xiorRepeatRequestsFilterPlugin(options?: object) {
//
export default function xiorRepeatRequestFilterPlugin(options = {}): XiorPlugin {
return function (adapter) {
return async (config) => {
return adapter(config);
};
};
}

0 comments on commit b079b42

Please sign in to comment.