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

Retry logic when rate-limited #525

Open
wants to merge 4 commits into
base: main
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
10 changes: 10 additions & 0 deletions docs/classes/google-spreadsheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,13 @@ Param|Type|Required|Description
`rangeId`|String|✅|ID of the range to remove


### Retry logic

### `setRetryOptions(metadataId)` (async) :id=fn-setRetryOptions
> Set the retry options for when your requests are rate-limited (error 429)
> If these options are not set then requests won't be retried

Param|Type|Required|Description
---|---|---|---
`retries`|Number|✅|The number of times a request should be retried
`retryDelay`|Number|✅|The time to delay in miliseconds between retry attempts
24 changes: 23 additions & 1 deletion lib/GoogleSpreadsheet.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ class GoogleSpreadsheet {
this._handleAxiosErrors.bind(this)
);

this._retries = 0;
this._retryDelay = 3000;

return this;
}

Expand Down Expand Up @@ -122,6 +125,11 @@ class GoogleSpreadsheet {
*/
}

setRetryOptions(retries, retryDelay) {
this._retries = retries;
this._retryDelay = retryDelay;
}

// TODO: provide mechanism to share single JWT auth between docs?

// INTERNAL UTILITY FUNCTIONS ////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -150,7 +158,21 @@ class GoogleSpreadsheet {

async _handleAxiosResponse(response) { return response; }
async _handleAxiosErrors(error) {
// console.log(error);
if (_.get(error, 'response.status') === 429) {
const config = error.config;
const retryCount = config.retryCount || 0;

if (this._retries > 0 && retryCount < this._retries) {
config.retryCount = retryCount + 1;

return new Promise((resolve) => {
setTimeout(() => {
resolve(this.axios(config));
}, this._retryDelay);
});
}
}

if (error.response && error.response.data) {
// usually the error has a code and message, but occasionally not
if (!error.response.data.error) throw error;
Expand Down