Mysql module running wrong script - Node Js

Asked

Viewed 109 times

0

I am developing a simple system of customer persistence, products and sale. I have made a API using the express and module Mysql, but something strange is happening and I really have no idea what it might be:

I own this route:

 app.post("/cliente/salvar", function(request, response){

    let cliente = request.body;

    let connection = dbConnection();

    if(cliente.id){
        clienteFactoryDAO.alterarCliente(connection, cliente, function(erro, result){
            response.send(result);
            if(erro != null) console.log(erro);
            connection.end();
        });
    }else{
        clienteFactoryDAO.salvarCliente(connection, cliente, function(erro, result){
            response.send(result);
            if(erro != null) console.log(erro);
            connection.end();
        });
    }

});

Note that it refers to a module method clientFactoryDAO, code of this method is like this:

this.salvarCliente = function(connection, objeto, callback){

    let sqlEndereco = utilCliente.createSaveAdressQuery(objeto.endereco);

    console.log(sqlEndereco);

    connection.query(sqlEndereco, function (error, results){
        if(error) throw error;
        objeto.id_endereco = results.insertId;

        //Depois que salva o endereco, usa-se o id persistido e salva-se o cliente
        let sql =  utilCliente.createSaveQuery(objeto);
        console.log(sql);
        connection.query(sql, callback);
    })

}

Note that I close the connection on the second connection.query, within the callback, because I can’t close before, since I need to first save the address to that customer and then, save the customer.

Well, the error: The accessed endpoint is correct but at the moment the connection.query(), it performs the product insertion query, I have no idea why! I’ve read the entire documentation of the module Mysql in the Github and, I have not yet succeeded in discovering! Am I closing connection right? I have tried using the method Destroy and nothing!

Thank you from the start and I apologize if I haven’t been clear enough in my doubt

  • You do not need to close the connection manually on each request. You can create it by starting the application, exporting it and reusing it on your routes.

  • @ruanmartinelli, you believe the connection is the cause of the problem?

  • I wouldn’t know for sure. I spoke more like a tip, opening a new connection every time you go to the bank is a relatively costly operation.

No answers

Browser other questions tagged

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