Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilitate this process, we opted to use GuerillaMail, a simple disposable email client with an available API. After completing the necessary setup by configuring the email through their platform, the code snippet below effectively handles the task in various scenarios:

private async getEmailId(sid_token: string, emailType: EmailType): Promise<string> {
        var mail;
        var mailToken = this.getSidToken(sid_token);

        //Continuously check inbox until the expected email arrives
        // Jest framework timeout prevents infinite loop
        while (!mail) {
            const result = await request(this.guerillaMailApiUrl)
                .get('')
                .query({
                    f: 'check_email',
                    seq: 0,
                    sid_token: mailToken
                });
            if (result.body.list != undefined) {
                mail = result.body.list.filter(m => m.mail_subject == emailType && m.mail_from == '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b7bfb3bbbe92b6bdbfb3bbbcfcb1bdbf">[email protected]</a>' && m.mail_read == 0)[0];
            }
            else {
                mail = undefined;
            }
        }
        return mail.mail_id;
    }

Despite its functionality, the service imposes a restriction of 20 requests per minute, leading to test failures.

Is there a way to control the frequency of requests?

LATER EDIT: After introducing a delay method:

async delay(ms: number) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

and integrating it before exiting the while loop:

await this.delay(5000);

Are there alternative methods to achieve this with improved efficiency and clarity?

Answer №1

A valuable tool I have utilized in my previous projects is called Bottleneck. You can find more information about it at this link.

const limiter = new Bottleneck({
  maxConcurrent: 20,
  minTime: 60000
});

while (!mail) {
  // implement the limiter here
  const result = await limiter.schedule(() => request(this.guerillaMailApiUrl)
    .get('')
    .query({
      f: 'check_email',
      seq: 0,
      sid_token: mailToken
    }));
  if (result.body.list != undefined) {
    mail = result.body.list.filter(m => m.mail_subject == emailType && m.mail_from == '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3b333f37321e3a31333f3730703d3133">[email protected]</a>' && m.mail_read == 0)[0];
  } else {
    mail = undefined;
  }
}

I trust that you will find this information helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to transfer a value to another component in React

Currently, I am working on a project where users can add, edit, or delete movies from a list. While the addition and deletion functionalities are working fine, I am facing challenges with the editing feature. In my Movie component, I have included a text i ...

Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place! I have a structured list like this XHTML <ul class = "query-list"> <li class="query"> something </li> <li class="query" ...

Is the ajax success function failing to work properly in JavaScript?

Although I've searched extensively on Stack Overflow, none of the similar questions seem to solve my issue. The problem I'm facing is that the success function is not triggering the alert message and I can't seem to figure out why. <form ...

I attempted to implement an AJAX function, but unfortunately, it is not displaying any output

I attempted to implement an AJAX function but the output is not displaying anything. var ajaxFunction = function(url, method, data = "") { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { ...

Uploading data through AJAX without saving it in the database

Can someone please assist me? I am encountering an issue where I am uploading multiple data using an AJAX request. The data appears to upload successfully as I receive a response of 200 OK, but for some reason, the data is not being stored in the database. ...

I'm struggling to include a link in my project card component - I've tried using both the Link tag and anchor tag, but so far, I haven't been successful in

I am having trouble getting the link tag to work properly in my UI. I have tried using both the link and anchor tags, but neither seems to be functioning as expected. Can someone please advise on how to fix this issue? https://i.sstatic.net/tAD7C.png I w ...

Creating customizable form fields based on user input in Laravel - here's how!

I am feeling a bit lost when trying to generate dynamic fields based on user input. For example, this field is where the user can enter how many fields they want to create: {!! Form::open(array('url' => 'home')) !!} <div clas ...

Handling Errors: Communicating with the Frontend

I'm facing a challenge with error handling in my authentication API calls. Whenever I trigger the 500 status from Express, my frontend (using Vue) only displays the message Request failed with status code 500 instead of something more informative like ...

What is the best way to incorporate one Div within another Div using JavaScript?

I have a single main div with an id, and I am looking to insert 4 additional child divs inside it. Each of these child divs will then contain 5 more divs each. The code snippet that I currently have is as follows: $( document ).ready(function() { for( ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...

The scrolltop animation does not appear to be functioning properly on iOS devices

I have implemented a JavaScript effect to increase the line-height of each list item on my website as you scroll. It works perfectly on my Macbook and Android Smartphone, but for some reason, it's not working on an iPhone. Can anyone provide a solutio ...

Display/Conceal Dropdown Menu for Combobox Using only Javascript

In my asp.net user control, I am generating markup that looks like this: <div id="combobox1"> <div id="combobox1_text"><span>combobox 1</span></div> <div id="combobox1_ddl"> <input type="checkbox" id="combobo ...

Receiving Server Emissions in Vue/Vuex with Websockets

In my Vue component, I was using socket.io-client for WebSocket communication. Now that I've added Vuex to the project, I declared a Websocket like this: Vue.use(new VueSocketIO({ debug: true, connection: 'http://192.168.0.38:5000', })) ...

Receiving a PNG image in the response of a REST call from ServiceNow, the data appears to be garbled with junk characters

I encountered an interesting situation where I received a PNG image as a response from a REST call in ServiceNow. The response seems to be filled with junk characters, making it difficult to work with as shown below. My goal is to write a server script tha ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Utilizing AngularJS in combination with Bootstrap's user-friendly UI date

Is there a way to manipulate the datepicker object so it can open and close as needed? Also, how can I access the datepicker object in a different directive within AngularJS? ** HTML ** <input type="text" class="form-control" uib-datepicker-popup="{{f ...

Executing Laravel Ajax Requests on the whole website

I have been encountering an issue with my Ajax post call in my application. The call is supposed to update the Navigation throughout the entire site, but it seems to be working on some pages and not others. I am looking for a way to fix this and make it mo ...

Encountering a TS(2322) Error while Implementing Observables in Angular 12

Exploring the intricacies of Angular 12 framework, I find myself encountering a hurdle in my learning journey. The tutorial I am following utilizes the Observable class to query fixed data asynchronously. However, an unexpected ts(2322) error has surfaced ...

The validation process is still failing even though the correct credentials have been entered

I'm diving into the world of Javascript and DOM today, but I've hit a roadblock. Can you take a look at this code snippet and help me figure out what's causing me to always end up in the else block, no matter what I input in the text field? ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...