polygon-io / client-js

The official JS client library for the Polygon REST and WebSocket API.
MIT License
190 stars 59 forks source link

Timeouts and retries #180

Open jdconley opened 1 year ago

jdconley commented 1 year ago

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 commented 1 year ago

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',
      },
    );
  }