Skip to content

Instantly share code, notes, and snippets.

@Aminechakr
Created March 13, 2023 09:48
Show Gist options
  • Save Aminechakr/95ce94861919b5e8c2d524ab4100256a to your computer and use it in GitHub Desktop.
Save Aminechakr/95ce94861919b5e8c2d524ab4100256a to your computer and use it in GitHub Desktop.
Scoring NodeJs Express API program

This program uses the Express framework to define an API with two endpoints: a POST endpoint to input the endpoint parameters (/endpoint) and a GET endpoint to retrieve the results (/endpoint).

The /endpoint POST endpoint expects a JSON body with three properties: url, name, and score. When a POST request is received, the endpoint parameters are added to the endpoints array.

The /endpoint GET endpoint makes requests to each of the endpoints in the endpoints array and returns a JSON object with the scores for each endpoint. The makeRequests function is called to make the requests and accumulate the scores. If any errors occur during the requests, they are logged to the console.

The startRequests function starts making requests on a fixed interval (in this case, every hour) using the setIntervalAsync function from the set-interval-async library. The interval variable is used to store a reference to the interval so it can be cleared later.

The setTimeout function is used to set a timer for 1 hour after the server starts. When the timer expires, the interval is cleared and the makeRequests function is called one final time to get the final scores.

Note that this program assumes that the endpoint parameters are valid URLs

const express = require('express');
const axios = require('axios');
const { setIntervalAsync } = require('set-interval-async/fixed');
const { clearIntervalAsync } = require('set-interval-async/fixed');
const app = express();
const port = 3000;
let endpoints = [];
// Define a function to make requests to all the endpoints
async function makeRequests() {
let scores = {};
for (const endpoint of endpoints) {
try {
// Make a request to the endpoint
const response = await axios.get(endpoint.url);
// If the request is successful, add the score to the scores object
if (response.status === 200) {
if (!scores[endpoint.name]) {
scores[endpoint.name] = 0;
}
scores[endpoint.name] += endpoint.score;
}
} catch (error) {
console.error(`Error making request to ${endpoint.url}: ${error.message}`);
}
}
return scores;
}
// Define a function to start making requests on a fixed interval
function startRequests() {
return setIntervalAsync(async () => {
const scores = await makeRequests();
console.log(`Scores: ${JSON.stringify(scores)}`);
}, 60 * 60 * 1000); // Run every hour
}
// Define the POST endpoint to input the parameters
app.post('/endpoint', (req, res) => {
const { url, name, score } = req.body;
endpoints.push({ url, name, score });
res.sendStatus(200);
});
// Define the GET endpoint to retrieve the results
app.get('/endpoint', async (req, res) => {
const scores = await makeRequests();
res.json(scores);
});
// Start making requests and set a timer for 1 hour
let interval = startRequests();
setTimeout(async () => {
clearIntervalAsync(interval);
// Get the final scores and log them to the console
const finalScores = await makeRequests();
console.log(`Final Scores: ${JSON.stringify(finalScores)}`);
}, 60 * 60 * 1000);
// Start the server
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
@Aminechakr
Copy link
Author

const express = require('express');
const app = express();
const axios = require('axios');
const bodyParser = require('body-parser');
const cron = require('node-cron');

app.use(bodyParser.json());

let endpoints = [];

app.post('/api/start', async (req, res) => {
  endpoints = req.body.endpoints.map(endpoint => ({
    ...endpoint,
    initialScore: endpoint.score // save initial score
  }));
  
  for (const endpoint of endpoints) {
    try {
      const response = await axios.get(endpoint.url);
      if (response.status === 200) {
        console.log(`${endpoint.name} - success (${response.status})`);
        endpoint.score += 100; // increment score by 100 on success
      }
    } catch (error) {
      console.log(`${endpoint.name} - error (${error.response.status})`);
    }
  }
  
  res.send('Monitoring started!');
  
  // schedule request every 30 seconds
  cron.schedule('*/30 * * * * *', async () => {
    for (const endpoint of endpoints) {
      try {
        const response = await axios.get(endpoint.url);
        if (response.status === 200) {
          console.log(`${endpoint.name} - success (${response.status})`);
          endpoint.score += 100; // increment score by 100 on success
        }
      } catch (error) {
        console.log(`${endpoint.name} - error (${error.response.status})`);
      }
    }
  });
});

app.get('/api/results', (req, res) => {
  const results = endpoints.map(({ name, score }) => ({ name, score }));
  res.json(results);
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment