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

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

Invoke a jQuery method in a dynamic manner

Is it possible to achieve the following? var todo = "text"; $this.eval(todo).split(/\b[\s,\.-:;]*/).length; The desired function is: $this.text().split(/\b[\s,\.-:;]*/).length; I'm struggling to find a solution... Ca ...

Tips for displaying only the initial 15 characters of a text value

The content extracted from a .ts file is being displayed on the home.html page. I am aiming to display only the initial 15 characters followed by 3 dots (...). Despite my efforts, the following code snippet is not functioning as expected: home.html < ...

Unable to transfer data successfully from popup to extension.js

I am currently developing a browser extension using Crossrider and I'm facing an issue with sending data from the popup to extension.js Here is my code for the popup: <!DOCTYPE html> <html> <head> <!-- This meta tag is relevant ...

What is the best way to duplicate several HTML input fields using jQuery?

My div is quite intricate with input fields structured like this <input type="text" name="firstname"> <input type="text" name="lastname"> <input type="text" name="email"> <input type="text" name="address"> <div id="section_toC ...

Embracing the node mindset with a Java foundation

As a Java Developer, I have become accustomed to working in a sequential manner where tasks are executed one after the other or concurrently with multiple threads. The organization of code in a sequential way seemed logical under this paradigm. However, wh ...

Upon selecting multiple checkboxes, corresponding form fields will be displayed based on shared attributes

When multiple checkboxes are selected by the user, corresponding form fields should appear based on the checkboxes. For example, if both flight and hotel checkboxes are checked, then the full name and last name fields should be displayed while other fields ...

How to Convert JSON from an Object to a String using jQuery?

Currently, I am utilizing the Ajax Form jQuery plugin to fetch JSON data from a server: /** * A convenient function for the jQuery AJAX form plugin. */ function bindOnSuccess(form, callback) { form.ajaxForm({ dataType: 'json', ...

Validate the date selected in a dropdown menu using JavaScript

I'm still relatively new to Javascript, just working my way through some tutorials. I have three select boxes in my HTML form as shown below. HTML Form: <table> <form id="enrolment" name="enrolment" onsubmit="return datevalidate();" action ...

Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body. Here is the client-side script: const form = document.getElementById('form1') form.addEventListener('submit', (e) => ...

Exploring test suite pathways while utilizing ArcGIS JSAPI as an alternative loader within the Intern framework

I have been developing an application using the ArcGIS Javascript API and incorporating tests with Intern. While working on Windows 7 under IIS, I encountered some challenges but managed to overcome them by following the Intern tutorial and referring to so ...

When using addClass("test"), it throws an error message: TypeError: undefined is not a function

Upon examination in the console, I discovered the following: $(".myCssClass")[0].parentNode <li><span class="myCssClass">some text</span></li> I am attempting to add a CSS class to the parent span tag within the <li> element ...

Utilizing ASCII art in React: A guide to incorporating textual designs into your

I'm having trouble displaying ASCII images correctly on my React app. I've tried various methods, but nothing seems to maintain the form when rendered in the browser. <Grid container id="terminal_banner"> <Grid item ...

Ways to set the base URL on the development server for a call to react-scripts start

I am facing an issue with configuring my primary PHP server to run the ReactJS dev server created using yarn start within a directory named /reactive on the PHP site (using nginx proxy_pass). The problem is that I cannot set the root of the node server to ...

The problem with the CSS Grid effect

Looking for assistance in creating a grid layout similar to the one on this website: Upon inspecting the page source, I found the following code snippet: http://jsfiddle.net/o45LLsxd/ <div ng-view="" class="ng-scope"><div class="biogrid ng-scope ...

Problem with Jsdom retrieving document

I am struggling to utilize jsdom for loading a local HTML file. Here is the code snippet: var config = { file: "filename", scripts: ["node_modules/jquery/dist/jquery.min.js"], done: function(err, window){ con ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

What are the potential drawbacks of combining the useState hook with Context API in React.js?

Within my code, I establish a context and a provider in the following manner. Utilizing useState() within the provider enables me to manage state while also implementing functions passed as an object to easily destructure elements needed in child component ...

How to detect a right-click on empty time slots in Fullcalendar agenda views

I am working with a calendar feature on my web application using Adam Shaw's fullcalendar 2.1.1 JS library. I have successfully set up right-click responses for events and days by binding the "mousedown" event in the dayRender and eventRender callback ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...