There is a code:

function isAuth(socket, next) { // Куча другого кода if (hash == sig) { connection.query('SELECT avatar_url FROM fm_profiles WHERE user_id = ?', [handshakeData._query.user_id], function(err, rows) { if (err) throw err; var ava = rows[0].avatar_url; handshakeData.avatar = ava; }); handshakeData.nick = handshakeData._query.username; handshakeData.user_id = handshakeData._query.user_id; handshakeData.mode = handshakeData._query.mode; next(); return; } next(new Error('not authorized')); } 

After a while he writes the following error:

 Error: Cannot enqueue Query after fatal error. 

There is a script to automatically raise MySQL, but after this error it does not work:

 function initializeConnection(config) { function addDisconnectHandler(connection) { connection.on("error", function (error) { if (error instanceof Error) { if (error.code === "PROTOCOL_CONNECTION_LOST") { console.error(error.stack); console.log("Lost connection. Reconnecting..."); initializeConnection(connection.config); } else if (error.fatal) { throw error; } } }); } var connection = mysql.createConnection(config); // Add handlers. addDisconnectHandler(connection); connection.connect(); return connection; } var connection = initializeConnection({ host : '127.0.0.1', user : 'root', password : 'xxx', database : 'xxx', }); 

Thank you in advance!

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Well, even this script would work. If you make a mistake, you create a new connection ... and forget it, leaving everyone to work with the old one!

In general, using a single database connection in a web server is a strange idea. After all, in parallel, many requests are made from different users - so, when the connection drops due to one user, all fly away?

Even creating a connection for each request - and that looks better. And in the library you use there are pools of connections - which are quite suitable for use.