NodeJS + Socket.IO + Mysql - mysql

I'm using socket.io in order to send message to the user when he join my site and initializing his details using cookie sent by the client. After a while and few refreshes performed my queries stop working.
Here's my code:
io.on('connection', function(socket) {
var user = false;
socket.on('hash', function(hash, gameType) {
socket.join(gameType);
query('SELECT * FROM `users` WHERE `hash` = ' + pool.escape(hash), function(err, row) {
if((err) || (!row.length)) return socket.disconnect();
user = row[0];
users[user.steamid] = {
socket: socket.id,
balance: parseInt(row[0].balance)
}
socket.emit('message', {
balance: row[0].balance,
type: 'hello',
user: row[0].steamid
});
}
}
function query(sql, callback) {
console.log(callback);
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
logger.info('DB Connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/site.log' }
]
});
var logger = log4js.getLogger();
var pool = mysql.createPool({
connectionLimit : 10,
database: 'test',
host: 'localhost',
user: 'root',
password: 'pw'
});
process.on('uncaughtException', function (err) {
logger.trace('Strange error');
logger.debug(err);
});

my guess is the reason is you exhaust the connection pool.
if(err) return callback(err); << after some erros here
connection.release(); << not released if there is an error
just release the connection before this line

Related

How to make return wait for MySQL connection to end? Node.js

I'm new to Node.js I'm testing some code on Wix to check my database if a account name already exists prior to allowing a new one to be created (I'm purposely not using the WHERE tag at the moment for learning purposes).
Currently the method check account name returns before the connection finishes, not allowing the check to take place properly.
Any help appreciated.
export function tryToCreateAccount(login, password)
{
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
if(checkAccountName(login, connection))
{
console.log("Name didn't exist.");
}
else
{
console.log("Name Existed.");
}
}
function checkAccountName(account_name, connection)
{
var accountNameAvailable = true;
connection.connect(function (err)
{
if(err) throw err;
connection.query("SELECT login FROM accounts", function (err, result)
{
if (err) throw err;
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == account_name)
{
console.log("Should of been false");
connection.end;
accountNameAvailable = false;
}
}
});
connection.end;
});
return accountNameAvailable;
}
I figured out why it wasn't doing anything, the next was getting called too late since the connection ended and next was within the connection code block.
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
export function tryToCreateAccount(login, password)
{
checkAccountName(login, connection, function(err, accountNameAvailable)
{
if(err || !accountNameAvailable){
console.log("Name didn't exist.");
}
else
{
console.log("Name Existed.");
}
})
}
function checkAccountName(login, connection, next)
{
var accountNameAvailable = false;
connection.connect(function (err)
{
if(err) next(err);
connection.query("SELECT login FROM accounts", function (err, result){
if (err) next(err);
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == login)
{
accountNameAvailable = true;
}
}
next(null, accountNameAvailable);
connection.end();
});
});
}
Welcome to Node.js (and the world of Async functions (and Promises (and Callbacks)))
I've written this in the "callback" style, but I highly recommend looking into async/await for something like this, as well as understanding how "promises" fit into the picture.
// to test, call tryToCreateAccount('login','pass',function(err,data){console.log(err,data)});
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'host',
user: 'user',
password: 'pass',
database: 'db'
});
export function tryToCreateAccount(login, password, next)
{
checkAccountName(login, connection, function(err, accountNameAvailable){
if(err || !accountNameAvailable){
console.log("Name didn't exist.");
next(err || 'Name didn't exist.')
}
else
{
console.log("Name Existed.");
next(null, true)
}
})
}
function checkAccountName(account_name, connection, next)
{
var accountNameAvailable = false;
connection.connect(function (err)
{
if(err) next(err);
connection.query("SELECT login FROM accounts", function (err, result){
if (err) next(err);
for(var i = 0; i < result.length ; i++)
{
if(result[i].login == account_name)
{
console.log("Should of been false");
connection.end;
accountNameAvailable = true;
}
}
connection.end();
next(null, accountNameAvailable);
});
});
}

Cannot use .query commands leaves to an error in nodejs

Problem:
I have created a node application there I am adding admin to the database like this in userModal.js file.
var bcrypt = require('bcryptjs');
var sql = require('../db.js');
module.exports.save_admin = (new_admin,callback) =>{
bcrypt.genSalt(10,(err, salt)=> {
bcrypt.hash(new_admin.password, salt, (err, hash)=> {
new_admin.password = hash;
if(err){
throw err;
}
else{
console.log(new_admin.password);
sql.query("INSERT INTO administrators set ?", new_admin, callback);
}
});
});
}
This is how I am calling this function from the controller.
var admin = {
first_name: req.body.first_name,
last_name: req.body.last_name,
organization: req.body.organization,
admin_level: req.body.admin_level,
user_identity: req.body.identity,
username: req.body.username,
password: req.body.password
};
User.save_admin(admin, (err,user) => {
if (!err) {
res.json({ state: true, msg: "data Inserted" });
} else {
res.json({ state: false, msg: "data Is Not Inserted" });
}
});
This is how I have configured the database in db.js file.
'user strict';
var mysql = require('mysql');
//local mysql db connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'mydatabase'
});
connection.connect(function(err) {
if (!err){
console.log("Database connection succeeded...!");
}
else{
console.log('Error in DB connection :'+JSON.stringify(err,undefined, 2));
}
});
module.exports = connection;
module.exports = {
"secret": "myapplicationsecret"
};
This setup leaves me this error.
sql.query("INSERT INTO administrators set ?", new_admin, callback);
^
TypeError: sql.query is not a function

How to create a awaitable connection with mysql using node.js

I'm new with Node.js and I'm trying to create a async method with Node.js, because I need to check a row inside of my database and then decide what to do with it. So I created a file called sql-service.js
const sql = require('mysql');
var connection = sql.createConnection({
host: '0.0.0.0',
user: 'foo',
password: 'fooo'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
console.log(connection.state);
module.exports.SignUpUser = (email,password)=>{
connection.query('select * from usuario', function(error, results, fields) {
console.log(results);
});
}
And inside of my Controller :
const sqlService = require('../services/sql-service');
exports.post = async(req,res,next)=>{
const Email = req.body.Email;
const Passw = req.body.Password;
console.log(dateT.getdate());
if (fluentValidation.validateEmail(Email) && fluentValidation.isValidLenght(Passw)) {
try {
await sqlService.SignUpUser(Email,Passw);
//emailService.send(req.body.Email,'Nome','Bem vindo ao hanggu');
} catch (error) {
console.log(error);
}
res.status(201).send({
Email: "Valid " + req.body.Email,
Password: Passw.length,
Send: 's '//Date : dateT.getDateTime()
});
} else {
res.status(500).send({
Error: "Email invalid"
})
}
}
It does connect but the result that I got it's undefined, I tried
console.log('The solution is: ', results[0].usuario);
But still.
what schema you select?
var connection = sql.createConnection ({
host: '0.0.0.0',
user:'foo',
password : 'fooo',
database : 'you_db'
});
test

Unable to make persistent mysql connection in node

I have a node mysql connection that used to work properly but since traffic started coming i am getting a strange error
Error: Connection lost: The server closed the connection.
This is the class that i'm using
const mysql = require('mysql');
class Database {
constructor() {
this.connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
}
module.exports = Database;
Can someone help as to why this is happening?
Edit: this is how i call the code
const database = new Database();
database.query(`select * from users...
`, [req.user.id, parseInt(req.body.after)])
.then(rows => {
appData[".."] = rows['ddd']
res.status(200).json(appData);
database.close()
}, err => {
return database.close().then(() => { throw err; })
})
.catch(err => {
console.log(err);
res.status(500).json("Database Error");
})
first create file ex database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: conf_core_sys.dbConfig.host,
user: conf_core_sys.dbConfig.user,
dateStrings: true,
password: conf_core_sys.dbConfig.pass,
database: conf_core_sys.dbConfig.dbName,
port:conf_core_sys.dbConfig.port,
debug: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}
second step :
let database = require("database")
let sql ="SELECT * from users";
database.query(sql, function (error, results, fields) {
if (error) {
callback(results)
} else {
callback(results)
}
})
some time ago i had the same problem, but at this time the probelm has not happened, maybe this solution helping you,
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}

Terminating a callback in nodejs

I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?
Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Use connection.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});