Skip to content

Commit

Permalink
Merge pull request #114 from FiorenMas/main
Browse files Browse the repository at this point in the history
fix Cloudflare rate limiting
  • Loading branch information
mrrfv authored Jun 9, 2024
2 parents a1fba53 + df645b6 commit a5d3fdb
Showing 1 changed file with 34 additions and 16 deletions.
50 changes: 34 additions & 16 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,23 +96,41 @@ const request = async (url, options) => {
"X-Auth-Key": API_KEY,
};

const response = await fetch(url, {
...options,
headers: {
...options.headers,
...headers,
},
});

const data = await response.json();

if (!response.ok) {
// Send a message to the Discord webhook if it exists
await notifyWebhook(`An HTTP error has occurred (${response.status}) while making a web request. Please check the logs for further details.`);
throw new Error(`HTTP error! Status: ${response.status} - ${ 'errors' in data ? data.errors[0].message : JSON.stringify(data) }`);
}
/*
Due to the undocumented Cloudflare API rate limit, the request will be retried until Cloudflare accepts it.
*/
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

let response;
let data;
let attempts = 0;

return data;
while(attempts < 50) {
try {
response = await fetch(url, {
...options,
headers: {
...options.headers,
...headers,
},
});

data = await response.json();

if (!response.ok) {
throw new Error('Response not OK');
}
return data;
} catch (error) {
attempts++;
if(attempts >= 50) {
// Send a message to the Discord webhook if it exists
await notifyWebhook(`An HTTP error has occurred (${response.status}) while making a web request. Please check the logs for further details.`);
throw new Error(`HTTP error! Status: ${response.status} - ${ 'errors' in data ? data.errors[0].message : JSON.stringify(data) }`);
}
await wait(5000);
}
}
};

/**
Expand Down

0 comments on commit a5d3fdb

Please sign in to comment.