My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders
based on their URLs and store the ones that return data in successfulResponses
within my app.component.ts
.
Promise.all(
orders.map(order => this.api.getURL(order.resource_url).catch(() => null))
).then(responses => {
const successfulResponses = responses.filter(response => response != null)
for(let data of successfulResponses) {
// additional requests are made with the retrieved data here
}
});
I have more than 50 orders
to process, but I can only handle a maximum of 50 at once due to the API restrictions. Therefore, in my service, I track the timestamp of the first request made. If the time difference between subsequent requests is over 60 seconds, I reset the request limit to 50. If it is less than 60 seconds, I check if there are available requests remaining. If yes, I proceed with the request; otherwise, I wait for one minute:
sleep(ms){
return new Promise(resolve => setTimeout(resolve, ms));
}
async getURL(){
if(!this.date){
let date = new Date();
this.date = date;
}
if((new Date().getSeconds() - this.date.getSeconds() > 60 )){
this.maxReq = 50;
this.date = new Date();
return this.http.get(url, this.httpOptions).toPromise();
} else {
if(this.maxReq > 0){
this.maxReq -= 1;
return this.http.get(url, this.httpOptions).toPromise();
} else{
console.log("wait");
await this.sleep(60*1000);
this.maxReq = 50;
this.date = new Date();
return this.http.get(url, this.httpOptions).toPromise();
}
}
}
However, the code in app.component.ts
does not properly synchronize with the getURL()
function, leading to an issue where too many requests are sent too quickly. How can I resolve this problem?