Home > database >  My API call creates a record even after the return statement?
My API call creates a record even after the return statement?

Time:01-17

this will be a simple answer, but I have this code, that validates if a record exists in the database, and It does, and I got a status 500 from the API call, but keeps creating the duplicate record in my table.

exports.createBet = async (req, res)=>{
        betBody = req.body;
        newBalance = 0.0;
        Bet.findOne({
            where: {
                [Op.and]: [
                    {match_id: betBody.matchId},
                    {user_id: betBody.userId}
                ]
            }
        }).then(data=>{
            if(data){
                return res.status(500).send({message: "Bet already made for this match"});
            }
        })
        .catch(err=>{
            return res.status(500).send({ message: "Error creation the bet: "   err.message});
        });
        balnce = await User.findOne({
            where:{
                id: betBody.userId
            }
        })
        .then(data=>{
            if(data.balance < betBody.betAmount){
                return res.status(500).send({ message: "Not enough balance to make that bet."});
            }
            return data.balance;
        })
        .catch(err=>{
            return res.status(500).send({ message : "Error getting the user in the bet creation: "   err.message})
        });
        Bet.create({
            match_id: betBody.matchId,
            bet_amount: betBody.betAmount,
            selected_winner: betBody.teamSelect,
            user_id: betBody.userId
        })
        .then(data=>{
            res.json(data)
        })
        .catch(err=>{
            return res.status(500).send({ message: "Error creating the bet: "   err.message})
        });
        newBalance = balnce - betBody.betAmount;
        User.update(
            { balance: newBalance},
            { where: {id: betBody.userId}}
        )
        .catch(err=>{
            res.status(500).send({ message: "Error getting user: "   err.message})
        });
    };

Here it is the response of the api call

And here it is the duplicated records in my table

CodePudding user response:

This problem causes in your database a saved record without all the fields trying to truncate your table and start a fresh,

I think here in your query all time finds a record(data) thats why we are facing this type of error

If it's not work try to debug your code with log your data which comes from your findOne query

CodePudding user response:

You should use the promise chain(or async/await correctly) to solve this issue, When a request reaches to createBet function every database call(without await one) is executing parallel, it creates a new record while checking for the existing one.

NOTE: Sometimes You might get a response already sent error. res.send does not stop execution it'll return the response but the remaining code will still execute.

exports.createBet = async (req, res) => {
  betBody = req.body;
  newBalance = 0.0;
  try {
    const bet = await Bet.findOne({
      where: {
        [Op.and]: [{ match_id: betBody.matchId }, { user_id: betBody.userId }],
      },
    }).catch((err) => {
      throw { message: "Error creation the bet: "   err.message };
    });

    if (bet) {
      throw { message: "Bet already made for this match" };
    }
    //... handle the cases like above, must use await
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
  •  Tags:  
  • Related