Skip to content

Commit 7950745

Browse files
authored
Automatically retry when rate limit is reached
1 parent 74aed06 commit 7950745

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

lib/Client.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,11 @@ private function buildUrl($queryParams = null)
134134
* @param string $url the final url to call
135135
* @param array $body request body
136136
* @param array $headers any additional request headers
137+
* @param bool $retryOnLimit should retry if rate limit is reach?
137138
*
138139
* @return Response object
139140
*/
140-
public function makeRequest($method, $url, $body = null, $headers = null)
141+
public function makeRequest($method, $url, $body = null, $headers = null, $retryOnLimit = true)
141142
{
142143
$curl = curl_init($url);
143144

@@ -169,8 +170,17 @@ public function makeRequest($method, $url, $body = null, $headers = null)
169170
$responseHeaders = array_map('trim', $responseHeaders);
170171

171172
curl_close($curl);
173+
174+
$response = new Response($statusCode, $responseBody, $responseHeaders);
175+
176+
if ($statusCode == 429 && $retryOnLimit) {
177+
$headers = $response->headers(true);
178+
$sleepDurations = $headers['X-Ratelimit-Reset'] - time();
179+
sleep($sleepDurations > 0 ? $sleepDurations : 0);
180+
return $this->makeRequest($method, $url, $body, $headers, false);
181+
}
172182

173-
return new Response($statusCode, $responseBody, $responseHeaders);
183+
return $response;
174184
}
175185

176186
/**

0 commit comments

Comments
 (0)