skip to Main Content

I have created a GET endpoint call router.get('/alarm1',authenticateUser, getSiteIds, async (req, res) => {//body}). I have created multiple routers like above one for alarm2,alarm3 and alarm4. Then I need to call each endpoint and return the responses of each router call, once I call the all-alarms endpoint router.get('/all-alarms',authenticateUser, getSiteIds, async (req, res) => {//body}) router call. But I could not find a way to do this. I found a way to do this using processes in node.js.

all-alarms.js file

const { spawn } = require('child_process');
const express = require('express');
const { getSiteIds } = require('../../middleware/sites/getSiteIds');
const { authenticateUser } = require('../../middleware/auth/authenticateUser');
const app = express();
const router = express.Router();
const path = require('path');

// Create the combined endpoint
router.get('/', authenticateUser, getSiteIds, async (req, res) => {
  const endpoints = [
    '/alarm1',
    '/alarm2',
    '/alarm3',
    '/alarm4'
    ];
  const bearerToken = req.headers.authorization; // Retrieve the bearer token from the initial request
  // Create an array to store the child processes
  const processes = [];

  // Function to handle each endpoint
  const handleEndpoint = (endpoint) => {
    return new Promise((resolve, reject) => {
      const process = spawn('node', [path.join(__dirname, '../../', 'call-alarms.js'), endpoint,bearerToken]);

      process.stdout.on('data', (data) => {
        resolve(JSON.parse(data));
      });

      process.stderr.on('data', (data) => {
        reject(data.toString());
      });

      process.on('exit', (code) => {
        console.log(`Child process exited with code ${code}`);
      });
    });
  };

  // Call each endpoint in parallel using child processes
  try {
    for (const endpoint of endpoints) {
      const process = handleEndpoint(endpoint);
      processes.push(process);
    }

    const results = await Promise.all(processes);

    // Combine the results into a single response
    const aggregatedData = {
      'alarm1': results[0],
      'alarm2': results[1],
      'alarm3': results[2],
      'alarm4': results[3]
    };

    res.json(aggregatedData);
  } catch (error) {
    res.status(500).json({ error: 'Error occurred while aggregating data.' });
  }
  //  finally {
  //   // Kill all child processes
  //   processes.forEach((process) => {
  //     // process.kill();
  //   });
  // }
});

module.exports = router;

call-alarms.js file

const axios = require('axios');

// Get the endpoint URL from the command line arguments
const endpoint = process.argv[2];

// Get the bearer token from the command line arguments
const bearerToken = process.argv[3];

// Make the HTTP request to the specified endpoint with the bearer token
axios.get(`http://localhost:3000${endpoint}`, {
  headers: {
    Authorization: bearerToken // Set the bearer token as the authorization header
  }
})
  .then((response) => {
    // Send the response back to the parent process
    process.stdout.write(JSON.stringify(response.data));
    process.exit(0);
  })
  .catch((error) => {
    // Send the error message back to the parent process
    process.stderr.write(error.message);
    process.exit(1);
  });

But, here the problem I face is I don’t need not include a http call for these already created router calls as axios.get(http://localhost:3000${endpoint}`. How can I do this using router call instead of axios http call? It is better if I can achive this without processes.

2

Answers


  1. You should separate your backend logic and the enpoints, in order to be able to re-use some parts of the code in different endpoints.

    const express = require('express');
    
    const app = express();
    const router = express.Router();
    
    function alarm1 () {
      return {
        "result": 'alarm1'
      };
    }
    
    function alarm2 () {
      return {
        "result": 'alarm2'
      };
    }
    
    router.get('/all-alarms', (req, res) => {
      res.json({
        "alarm1": alarm1(),
        "alarm2": alarm2()
      });
    });
    router.get('/alarm1', (req, res) => {
      res.json(alarm1());
    });
    
    router.get('/alarm2', (req, res) => {
      res.json(alarm2());
    });
    
    
    Login or Signup to reply.
  2. this is simple way to create multiple routes in single endpoints

    // this is the routes.js file

    const express = require(‘express’);
    const router = express.Router();

    router.get(‘/’, Router 1)

    // router2

    router.get(‘/’, ‘Router 2’ )

    module.exports = router;

    // this is app.js file

    const express = require(‘express’);
    const app = express();

    const router1 = require(‘./router1’);
    const router2 = require(‘./router2’);

    app.use(‘/endpoint’, router1);
    app.use(‘/endpoint’, router2);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search