ofetch icon indicating copy to clipboard operation
ofetch copied to clipboard

Custom retry logic

Open stychu opened this issue 8 months ago • 1 comments

Describe the feature

Having a retry on specific status codes is great but could we get a more customizable way of getting a retry to happen? I think this is a common use case to retry a request if the response doest match criteria.

Now I need to do custom wrapper logic to get such functionality.

//custom wrapper
export async function retryCall<T>({
  callback,
  maxRetries = 5,
  isResponseMatch,
  delayMs = 1000,
}: {
  maxRetries?: number;
  isResponseMatch: (data: T) => boolean;
  callback: () => Promise<T>;
  delayMs?: number;
}): Promise<T> {
  for (let attempt = 1; attempt < maxRetries; attempt++) {
    try {
      const response = await callback();

      if (isResponseMatch(response)) {
        return response;
      }
    } catch (error) {
      throw error;
    }

    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }

  return await callback();
}
await retryCall({
      callback: () => ofetch(...),
      isResponseMatch: (data) => data === 'success',
    })

Additional information

  • [ ] Would you be willing to help implement this feature?

stychu avatar Jun 12 '25 08:06 stychu