Search code examples
node.jsvariablesgetendpoint

How to pass variable to endpoint nodejs


I have 2 endpoints.

  1. It's: a) receive data from client b) + save this to file c) + counts how many times data is saved.
    app.post('/api/v1', (req,res) => {

      var data = req.body;
      console.log(req.body)

      const storeData = (data, path) => {
        try {
          console.log("Uploading data to file...")
          fs.appendFileSync(path, JSON.stringify(data))
          counter = counter +1;
          console.log(counter);
        } catch (err) {
          console.error(err)
        }
      }
    storeData(data,'./files/data.json');
  1. It's: a) Send data do client
app.get('/api/counter', (req, res) => {
  res.status(200).send({

  })
});

My question is :

"How can I modify second endpoint to get counter from first endpoint and send it to client?


Solution

  • You're basically asking for a simple state management module.

    I would recommend using a global counter to store the count. Increment the counter in the first endpoint and then access the same in the second. Or else setup an external state management for the same - either storing the counter in a file system or a db (not recommended)

    var counter;
    
    function setCount(num=0){
        counter = num;
    }
    
    function inc(){
        counter++;
    }
    
    function getCount(){
        return counter;
    }
    
    module.exports = {
        inc: inc,
        setCount: setCount,
        getCount: getCount
    };
    

    In your file with the API endpoints

    const arb = require('./path/name_of_your_arbitrary_file');
    
    ...
    // Increment in 1st endpoint
    arb.inc();
    
    ...
    // Get Count in 2nd endpoint
    var count = arb.getCount();