laiso / test

0 stars 0 forks source link

Add healthcheck endpoint to src/index.js #2

Closed laiso closed 3 months ago

laiso commented 3 months ago

Adding a Healthcheck Endpoint to src/index.js

Here's how you can add a healthcheck endpoint to your src/index.js file:

const express = require('express'); // Import express
const fetch = require('node-fetch');

const app = express(); // Create express app

// Existing getStatusCode function
function getStatusCode() {
  return fetch('https://google.com').then((res) => {
    console.log(res);
    return res.status;
  });
}

// Healthcheck endpoint
app.get('/healthcheck', async (req, res) => {
  try {
    const status = await getStatusCode();
    // Check status and respond accordingly
    if (status >= 200 && status < 300) {
      res.status(200).send('OK');
    } else {
      res.status(500).send('External service unavailable');
    }
  } catch (error) {
    res.status(500).send('Error checking health');
  }
});

// ... rest of your application code

app.listen(3000, () => console.log('Server listening on port 3000!'));

Explanation:

  1. Import Express: We need the express library to create a web server and define routes.
  2. Create Express App: We initialize an Express application using express().
  3. Healthcheck Endpoint:
    • We define a route /healthcheck using app.get.
    • Inside the route handler, we use the getStatusCode function to check the status of an external service (Google, in this case).
    • Based on the status code returned, we send an appropriate response:
      • 200 OK if the external service is available.
      • 500 Internal Server Error if there's an issue with the external service or an error during the check.
  4. Start Server: Finally, we start the server on port 3000.

Additional Considerations:

Remember to install Express:

npm install express

With these changes, you will have a basic healthcheck endpoint available at /healthcheck that you can use to monitor the health of your application.