Implementing long polling in express with a mocking approach

In order for my frontend to display a list with names and scores, it requires the following data:

[{id: 1, name: 'james', score: null}, {id: 2, name: 'john', score: null}]

The frontend will need to make repeated calls every second as the score values will be generated by the backend at a later time.

Therefore, the frontend will keep calling the endpoint every second until all the scores are returned.

Here are the steps detailing how the frontend should retrieve the data from the backend:

  1. Initiate the first call

[{id: 1, name: 'james', score: null}, {id: 2, name: 'john', score: null}]

  1. Render the names
  2. Display loading indicator for scores

  3. Make the second call

[{id: 1, name: 'james', score: 1.2}, {id: 2, name: 'john', score: 2.2}]

  1. Data retrieval complete, remove loading indicator

I am looking for a way to mock an endpoint in express that can provide this result to the frontend. My challenge lies in creating a non-persistent function in express that mimics when the score values will be returned.

Answer №1

To automate scoring, consider starting a timer to update scores over time if none have been set yet:

 const data = [/*...*/];

 let loading;
 function autoUpdateScores() {
   for(const el of data)
     el.score = Math.random();
 }

 app.get("/api/", (req, res) => {
   if(!loading) loading = setTimeout(autoUpdateScores, 5000);

   res.json({ data });
 });

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

Title: Propagating error responses through nested async/await try/catch blocks in NodeJS

I'm struggling to handle error responses in nested try/catch blocks within an Express route handler. In the given code snippet, I want the route handler to stop execution if an error is caught in the inner Try/Catch 3 block, resulting in a 404 status ...

What is the alternative method for sending a response in Express when the res object is inaccessible?

At this specific point in my code, I find myself unable to access (req, res, next) of express. Consequently, express is incapable of reaching my code to execute my function. As I am working within the mongoose pre('save') middleware, I am encryp ...

Choose your options effortlessly with CSS or JavaScript dropdown menus

As a novice web developer, I am contemplating whether dropdown menus are more suitable to be coded in CSS or JavaScript. What are the advantages and disadvantages of each approach? ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

Transfer picture information to the server on Internet Explorer versions 8 and 9

When it comes to sending image data to a server in FF and Chrome, we can use the following code: canvas.toDataURL("image/png"); This base 64 string is then decoded and extracted on the server. However, I am currently facing an issue with IE. Right now, t ...

Ways to change a variable in one file using another

My log.js, var data ; var winston = require('winston'); var config = {'status':1}; module.exports.config = config; In the get.js file (where I intend to update log.js), exports.getcategories = function (req, res) { if(log.stat ...

Is the Ajax DataType response JSON showing as "OK" but the output is blank?

So, I'm facing a challenge here. I have a basic jQuery Ajax request that isn't working when I set the DataType to "JSON". var form_data = { "id": msg, "token": token }; $.ajax({ type: 'POST', url: "ajax.php", ...

Receive emails: using the require() function with ES Module

After following the react-email documentation, I encountered an error when trying to run the yarn email command: $ email dev --port 3001 ***\node_modules\ora\index.js:65 if (process.platform === 'win32') { ...

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

What is the best way to bundle an Express server into an Electron application?

Currently in the process of developing an Electron app using vue-cli-electron-builder. My setup includes a local MySQL database and an Express server. I am wondering how to bundle my Express server with the Electron app? The Express server is used for d ...

Puppeteer-created PDF text may result in strange characters when copied and pasted

After using the most recent version of puppeteer to create the PDF attached, I noticed that when attempting to copy and paste text from Adobe Acrobat, it appears as: This is a test string. transforming into Țħįș įș ǻ țěșț șțřįňģ. B ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Why is it that useEffect is functioning correctly only on the first occasion?

Recently, I've been facing significant challenges with React's useEffect and States. The issue arises when I redirect to the main page of my app and then attempt to use them again. In the following component, everything seems to function correct ...

JavaScript calculations are not functioning as anticipated

I am encountering an issue with a gridview that contains a row where integer values, such as 7000, are being added. My goal is to calculate the total of all these rows and display it in a textbox after 2-3 rows have been added. To achieve this, I have im ...

"Is there a JavaScript code snippet that can retrieve information from a JSON file

Is there a way to create a custom JavaScript function that can extract specific data from a JSON object based on certain keywords? I am working with a Task Manager API and would like to automatically populate fields based on the task title. Here is an exam ...

Mongo experiencing "Topology destroyed" error following single connection

I am currently facing an issue with my MongoDB setup on mLab and Node.js using express and TypeScript. The problem arises when I try to make multiple requests to the database after starting my server, as each subsequent request throws an error stating "Top ...

Phaser multiplayer game encountering loading issue with the "script" element

Is there a recommended way to set up the server for this template? This tutorial by nkholski might be helpful: https://github.com/nkholski/phaser3-es6-webpack. Another resource I found useful is this guide on creating a basic multiplayer game in Phaser 3 w ...

What could be causing htmlparser2 in Node.js to add extra nodes during document parsing?

Seeking to extract the HTML content of a webpage using node so I can process its DOM to create something unrelated. It's crucial to accurately obtain the DOM representation from the HTML in order to properly process it. Utilizing htmlparser2 for this ...

How can I effectively develop a versatile user interface for a website using Ruby on Rails that is compatible with all

Currently, I am in the midst of developing a web application using Ruby on Rails. Occasionally, I encounter challenges with cross-browser compatibility when it comes to CSS and Javascript. Are there any strategies you recommend to reduce these issues dur ...

What is the best way to temporarily lock a section's position on a page?

I'm interested in learning how we can keep a particular section fixed in position temporarily, similar to the example provided below. In the link above, the Apple Watch product remains fixed while the content on the right side moves slightly before t ...