Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code for handling rate limits #186

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ composer.lock
*.sh
script/*

# IDE
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not required, you should be able to add IDE specific ignores to your global .gitignore and not the projects gitignore.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

.idea

# Testing
/phpunit.xml
/build
Expand Down
33 changes: 33 additions & 0 deletions src/Bigcommerce/Api/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ class Connection
*/
private $contentType;

/**
* Total number of times to automatically retry request if API rate limit is reached.
*/
private $maxRetries = 3;

/**
* Number of times request has been retried.
*/
private $autoRetries = 0;

/**
* Initializes the connection object.
*/
Expand Down Expand Up @@ -281,6 +291,13 @@ private function handleResponse()

$status = $this->getStatus();

if ($this->apiRateLimitReached($status)) {
if ($this->autoRetries < $this->maxRetries) {
$this->autoRetries++;
return $this->replayRequest();
}
}

if ($status >= 400 && $status <= 499) {
if ($this->failOnError) {
throw new ClientError($body, $status);
Expand All @@ -297,13 +314,29 @@ private function handleResponse()
}
}

$this->autoRetries = 0;

if ($this->followLocation) {
$this->followRedirectPath();
}

return $body;
}

public function apiRateLimitReached($status)
{
return $status == 429;
}

public function replayRequest()
{
$secondsToWait = $this->getHeader('X-Retry-After');
sleep($secondsToWait);
curl_exec($this->curl);

$this->handleResponse();
}

/**
* Return an representation of an error returned by the last request, or false
* if the last request was not an error.
Expand Down