Return query result with node

0

When I do a select in my MYSQL , I get the answer and I can display this for the user, but the problem is that this is not enough, just get the result and display it, I need to, for example, check if a given id has data in a table, and if it does not have it, do 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 thank you too much.

    
asked by anonymous 20.12.2017 / 15:11

1 answer

0

Why do not you pass a callback function to execSQLQuery execute with result instead of passing the object res ?

It would look 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 done.

    
03.01.2018 / 18:34