How to use rowCount to limit the number of records in a postgresSQL database using Node js?

Asked

Viewed 87 times

-1

I’m using the script to do this, but I get the error Internal server error. Anyone knows what I’m doing wrong?

var sqlQtd = db.query(`SELECT COUNT (*) FROM segunda`, function(err, result){
    return result.rowCount;
});

if(sqlQtd >= 44){
    return res.send("O HORARIO ESTÁ CHEIO");
}
  • Which lib you are using to access the database?

  • I’m using postgresql with Pool

2 answers

0

To implement the desired behavior, vc can do the following flow:

exports.countElements = (req, res, next) => {
    const sql = 'SELECT COUNT (*) FROM segunda';
    postgres.query(sql, (err, result) => {
        if (err) {
            return res.status(500).json({ errors: [{ location: req.path, msg: 'Houve um erro'}] });
        }
        if (result.rows.length >= 44) {
            return res.status(400).json({ errors: [{ location: req.path, msg: 'O HORARIO ESTÁ CHEIO'}] });
        }
        //...fazer suas coisas...
        next();
    });
};

In my example I used the return pattern json, but can return the values the way you are already doing.

If you need more examples, just post here.

I hope I’ve helped.

  • Hello! thanks for the reply. I used the script that Voce but it seems that it is ignoring the condition and is registering in the bank anyway

  • You did not post the registration code. this validation must be before the registration. Besides in my example I used the return as json, in your vc sends a send()

  • The registration code vc refers to the code where I use INSERT INTO to enter the records in the database?

  • Yes. Correctly.

  • It is being used before, the input code is that // put values inside the database const query = INSERT INTO segunda("nome", "cpfSegunda")
 VALUES ($1, $2) const values = [name, cpfSecond]; db.query(query, values, Function(err){ //error flow if(err){ //cont04 = cont04-1; Return res.send("Database error. Maybe CPF has already been uploaded." ) } //ideal flow Return res.redirect("/Cultsegunda"); });

  • Yes, you said yourself that it is being used later, the correct is to check the quantity before making the insertion. You can edit your question to add additional information.

Show 1 more comment

0

I recommend that you make use of modules to make your life easier by working with nodejs, and look for a package for postgree that works with promises.

Suppose you have a file called DB.js done as follows:

module.exports = {
   limite: () => new Promise((resolve, reject) => {
      db.query(`SELECT COUNT (*) FROM segunda`, function(err, result){
         if(err)
            return reject(err);

         return resolve(result.rowCount);
      })
   })
};

We can proceed in several ways, but the easiest way would be to control such a limit on the route you need, so if you have something like:

const DB = require('DB.js');
app.post('insert/registro', async (req, res) => {
   try{
      const limite = await DB.limite();
      
      if(limite > MEU_LIMITE_AQUI)
        throw Error('Limite maximo atingido');

      // Daqui em diante só inserir o teu código de insert...
   } catch(e){
      res.status(413); // Forbidden status header
      res.send({ error:'O HORARIO ESTÁ CHEIO' });
   }
});

If you need to implement this control on more routes, you can add the Danizavtz response and use this control as a middleware, would look something like:

const controller = require('MODULO CRIADO NA RESPOSTA DO Danizavtz');
app.post('insert/registro', controller, (req, res) => {
   // aqui dentro você pode fazer o insert sem precisar fazer nenhum controle
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.