Return query result with Node

Asked

Viewed 1,194 times

0

When I make a select in my bank MYSQL, I get the answer and I can display it to the user, but the problem is that this is not enough,just take the result and display it, I need for example to check if a given id has data in a table, and if not, do the INSERT.

This is my code on the server side.

app.post('/companies', function(req, res) {

    console.log('enviado do app'+req.body.id);

    let filter = '';
    filter = ' WHERE id_companies=' + req.body.id;
    execSQLQuery('SELECT * FROM companies' + filter, res); 
    "é aqui que eu preciso usar a variável results que eu recebo lá embaixo para continuar"
});

//inicia o servidor
app.listen(port);
console.log('API funcionando!');

function execSQLQuery(sqlQry, res){
  const connection = mysql.createConnection({
    host     : '***************',
    port     : 1111,
    user     : '**************',
    password : '************',
    database : '****************'

  connection.query(sqlQry, function(error, results, fields){
      if(error) 
        res.json(error);
      else
        res.json(results);


      connection.end();

      console.log('executou!');

  });

}

If anyone can help me, I’d appreciate it.

1 answer

0

Why don’t you pass one callback function to the execSQLQuery run with the result instead of passing the object res?

Would something like this:

app.post('/companies', function(req, res) {
  // ...

  execSQLQuery('SELECT * FROM companies' + filter, function(
    error,
    results,
    fields
  ) {
    // Faça qualquer operação que quiser aqui...

    res.json(error || results)
  })
})

// ...

function execSQLQuery(sqlQry, callback) {
  const connection = mysql.createConnection({/* ... */})

  connection.query(sqlQry, function(error, results, fields) {
    connection.end()

    callback(error, results, fields)
  })
}

This way you can perform any operation within the callback function and call res.json when you’re done.

Browser other questions tagged

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