client-js icon indicating copy to clipboard operation
client-js copied to clipboard

Timeouts and retries

Open jdconley opened this issue 1 year ago • 1 comments

I've run into issues recently where Polygon is sometimes taking minutes to timeout on requests so was just looking into timeouts and retries. It'd be quite useful if there was a builtin way to specify the request timeout and retry semantics.

If you used something like fetch-retry under the hood and let us supply options that'd be helpful.

And likewise a timeout option that used an AbortController signal with fetch would be great.

jdconley avatar Sep 28 '23 16:09 jdconley

FWIW I went with something like this as a wrapper, using retry-as-promised.

  private makeRequest<TResult>(
    action: (client: IRestClient) => Promise<TResult>,
  ): Promise<TResult> {
    return retry(
      async () => {
        const timeoutController = new AbortController();
        const client = restClient(
          this.polygonApiKey,
          'https://api.polygon.io',
          {
            signal: timeoutController.signal,
          },
        );
        const timeout = setTimeout(
          () => timeoutController.abort('Timeout calling Polygon API'),
          5000,
        );

        try {
          return await action(client);
        } finally {
          clearTimeout(timeout);
        }
      },
      {
        max: 5,
        name: 'Polygon API',
      },
    );
  }

jdconley avatar Sep 28 '23 22:09 jdconley