Areg
Areg

Reputation: 1485

Express.js how to prevent request if another one is being handled?

is there a way to prevent request if another one is being handled at the moment in express.js. I have a code like this

 try {
    if (currency == 'BTC') {
      let options = {
        symbol: symbol,
        side: 'BUY',
        type: 'MARKET',
        quantity: amount,
        timestamp: Date.now()
      }

      let order = await api.placeOrder(options);
      if (order.status == 200) {
        res.status(200).send({ message: 'Order successfully placed' });
      } else {
        res.status(500).send({ message: 'Failed to place order' });
      }
    } else if (currency == 'DASH') {
      let options = {
        symbol: 'DASHUSDT',
        side: 'BUY',
        type: 'MARKET',
        quantity: amount,
        timestamp: Date.now()
      }

      let order = await api.placeOrder(options);

      if (order.status == 200) {
        res.status(200).send({ message: 'Order successfully placed' });
      } else {
        res.status(500).send({ message: 'Failed to place order' });
      }
    } else {
      res.status(400).send({ message: 'Invalid currency' });
    }
  } catch (err) {
    console.log(err);
    res.status(500).send({ message: 'Internal server error' });
  }

Which basically allows users to buy bitcoin through the website, the problem is that sometimes one account can be used by more than two people and just in case if they will press buy button at the same time it would place orders twice. Is there a way to disallow other user to place an order if one is being processed at the moment?

Upvotes: 1

Views: 579

Answers (1)

TKoL
TKoL

Reputation: 13912

This is a super crude example and it may not take into account all your needs, but... maybe it will?

const locks = {};

app.post('route', function(req, res) {
    const routeLockKey = 'route:' + user.id;
    if (locks[routeLockKey]) return res.error; // error here somewow

    // if we got here, the route isn't locked for this user
    locks[routeLockKey] = true;
    try {
        // your code here
    } catch(e) {
        // error handling here
    } finally {
        delete locks[routeLockKey];
    } 
    
});

Upvotes: 2

Related Questions