hapi and mysql on nodejs - javascript

When I run the server there are no error. But when I visit the site it starts to give out an error TypeError: Converting circular structure to JSON
my database.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test'
});
module.exports = {
connection: connection
}
My products.js
var db = require('../database');
function getProducts(request) {
var product = db.connection.query('SELECT * from products', function(err) {
// connected! (unless `err` is set)
});
request.reply(product);
}
I just started with node.
update
db.connection.query('SELECT * from products', function(err, results) {
if (err) throw err;
console.log(err);
var products = results;
});
returning null on console.
update
var query = db.connection.query('SELECT * from products;', function(error, rows, fields) {
console.log(rows);
var products = rows;
});
it seems like adding ; to the end of the query did it.
Another thing is now products is not defined
function getProducts(request) {
if (request.query.name) {
request.reply(findProducts(request.query.name));
}
else {
request.reply(products);
}
}
As for the answer of the last question:
var products = query._results;

Related

Getting mysql result from javascript function in node.js

I am trying to get MySQL to result from the function.
At moment I am trying to set results from function to global array, but this doesn't work.
I am not very familiar with NodeJS or Javascript but I think it's a scope issue.
How would one do this in a proper way? Do I need to use async or maybe return results from a function?
This is what I have at moment.
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'xxxx',
port : '3306',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx'
});
var db_members =[];
get_members();
console.log(db_members); //outputs []
function get_members(){
connection.query("SELECT * FROM users", (err, result, fields)=>{
if (err) throw err;
result.forEach(function(row) {
db_members.push(row.username);
});
console.log(db_members); //this works
});
}
connection.query is async function so you are not able to get the result synchronously.
It is needed to make get_members to return Promise as the return value so to get the result asyncronously when using it..
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'xxxx',
port : '3306',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx'
});
function get_members() {
return new Promise((resolve, reject) => {
connection.query("SELECT * FROM users", (err, result, fields)=>{
if (err) return reject(err);
var db_members = [];
result.forEach(function(row) {
db_members.push(row.username);
});
return resolve(db_members);
});
});
}
get_members()
.then((members) => {
console.log(members); // This will work.
})
.catch((error) => {
console.error(error);
});

What is the correct way to be using the Node.js MySQL Library?

Currently I am playing around with the MySQL library in Node.js however I have a question about the correct/most efficient way to be using this library.
According to w3schools the correct way to make a single query is to use code like this
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
However, say I wanted to make multiple queries which would be executed by an event for example how would I handle this? Should I create an "initialise" function which is executed as soon as the program runs such as this?
var mysql = require('mysql');
var database;
//Initialise database
function setupDatabase() {
database = mysql.createConnection({
host: token.host,
user: token.user,
password: token.password,
database: token.database,
port: token.port
});
}
//Imagine this could be called at any time after execution
function event() {
if(database != null) {
database.connect(function(err) {
if (err) throw err;
database.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
And also do I have to connect to the database each time I make a query or can I add the "database.connect" call to my setupDatabase function such as this?
var mysql = require('mysql');
var database;
//Initialise database
function setupDatabase() {
database = mysql.createConnection({
host: token.host,
user: token.user,
password: token.password,
database: token.database,
port: token.port
});
if(database != null) {
database.connect(function(err) {
if (err) throw err;
});
}
}
//Imagine this could be called at any time after execution
function event() {
if(database != null) {
database.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
}
My main concern is that calling the con.connect function every single time I make a query would be slow and although these are asynchronous I want to be using the correct/most efficient way possible. Feel free to correct me on any mistakes with the last two code snippets I have only tested the first one so far.
You have to make database connection only once per application livetime (unless you have disconnects). Then you may have as much queries as you want.
Just put database connection routine somewhere in sepparate file and then require it in your applicatin initialisation step.
// mysql.js
const mysql = require('mysql');
module.exports = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
Or require it anywhere you need database connection - it will return connected database object without reruning that code again and again.
// inex.js
const databse = require('./mysql')
database.query("SELECT * FROM customers")
I created a file which include a function that holds a pool and handles the connection to the database like this
let _this = {};
let POOL = null;
function getPool() {
return new Promise((resolve, reject) => {
if(POOL != null) {
resolve(POOL);
} else {
//create connection pool
POOL = connectionPool;
resolve(POOL);
}
});
}
function closePool(){
// close pool here
}
_this.getPool = getPool;
_this.closePool = closePool;
module.exports = _this;
Now you can call getPool() and will recive a pool of connections where you can execute your queries with.

Passing variable from one js to another js file in nodejs

I'm just getting started with Nodejs, so please bear with me
I store my DB setting on the first JS, connect.js :
var mysql = require('mysql');
module.exports = function(connectDB) {
var connectDB = {};
connectDB.connection = mysql.createConnection({
//db params
});
connectDB.connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
return connectDB;
};
Then I stored my query in another JS file, lets call it dbManager.js :
var db = require('./connect')(connectDB);
var test_connection = connectDB.connection.query('SELECT * FROM `test`', function (error, results, fields) {
console.log(results);
});
exports.test = test_connection;
My goal is to pass the connection variable from connect.js to dbManager.js, so I could use it for running some queries.
The above code return an error, which said the variable is not passed successfully to dbManager.js :
ReferenceError: connectDB is not defined
Thanks in advance
The syntax error is because you cant define variables within an object literal using var.
e.g., you can't do the following,
var t = {
"r": 4,
var g = 5;
};
You can do this,
var t = {
"r": 4,
"g" : 5
};
And to access the properties of the object you can do,
console.log(t["r"]);
console.log(t.g);
In your code the problem is declaring a variable inside an object literal. Yo could do,
var connectDB = {};
connectDB.connection = mysql.createConnection({
//DB params
});
connectDB.connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connectDB.connection.threadId);
});
return connectDB;
Edit1 As per OP's comments,
connect.js:-
Changes- No need of the connectDB param, using module.exports functionality.
var mysql = require('mysql');
var connectDB = {};
connectDB.connection = mysql.createConnection({
//db params
});
connectDB.connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connectDB.connection.threadId);
});
module.exports = connectDB;
dbManager.js:-
var db = require('./connect');//removed the parameter
//use db variable to process queries as returned from the above require statement.
var test_connection = db.connection.query('SELECT * FROM `test`', function (error, results, fields) {
console.log(results);
});
exports.test = test_connection;
**you can do it like this
connection.js**
var mysql=require('mysql');
// Database Connection
var connection = mysql.createConnection({
host : hostname,
user :username,
password : password,
database : databasename,
multipleStatements:true
});
try {
connection.connect();
} catch(e) {
console.log('Database Connetion failed:' + e);
}
module.exports=connection;
**you can use this connection file in your dbmanager file like
this..**
var db = require('./connection.js');var test_connection =
connection.query('SELECT * FROM test', function(err,result) {
console.log(result);
});
Will something like this work for you? You can have a file that returns a connection object from the pool:
var mysql = require('mysql');
module.exports = function() {
var dbConfig = {...};
var database = mysql.createPool(dbConfig);
return {
getConnection: function(callback) {
// callback(error, connection)
database.getConnection(callback);
}
};
};
Wherever you need to use it, you can require it as follows:
var connector = require('./db-connector')();
Then use it like this:
connector.getConnection(function(error, connection) {
// Some code...
// Be sure to release the connection once you're done
connection.release();
});
This is how I store config data to pass around on my node server. I call it config.js and .gitignore it. I keep a sample copy called config.sample.js
let config = {};
config.mysql-host='localhost' || process.env.MYSQL_HOST;
config.mysql-user='me' || process.env.MYSQL_USER;
config.mysql-secret='secret' || process.env.MYSQL_SECRET;
config.mysql-database='my_db' || process.env.MYSQL_DB;
module.exports = config; //important you don't have access to config without this line.
To use it I would do the following.
const config = require('./config');
const mysql = require('mysql');
const connection = mysql.createConnection({
host: config.host,
user: config.user,
password: config.password,
});
connection.connect((err) => {
if(err) {
console.error(`error connecting: ${err.stack});
return;
}
console.log(`connected`);
});
const test_connection = connectDB.connection.query('SELECT * FROM `test`'(error, results, fields) => {
console.log(results);
});

getting Error: ER_PARSE_ERROR while inserting a dynamic values using node js and mysql

I am trying to insert the dynamic field values to mysql database using node js. In my server console am getting this error:
{ [Error: ER_PARSE_ERROR: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near
'[object Object]'f2a06305-7e98-4462-9ba2-72ce85fa4d32','undefined',
'59a3ff90-aa4a' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlState: '42000',
index: 0
}
What does the error mean and how do I resolve it? Below is the server code:
var mysql=require('mysql');
var http=require('http');
var uuid = require('node-uuid');
var path=require('path');
var express=require('express');
var app=express();
var bodyparser=require('body-parser');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
var myconnection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "siva"
});
app.use(express.static(__dirname + ""));
var uqid= uuid.v1();
var it_id=uuid.v4();
var tt=1;
var status="active";
app.post("/insert",function(req,res){
console.log(req.body);
/* TODO: Now just check that your drive function is correct, SQL is correct and whether what arguements passed to SQL callback is correct */
myconnection.query('Insert into cate_tbl (`cat_id`,`cat_name`,`cat_desc`,`cat_view_count`,`cat_status`) VALUES ("'+uqid+'","'+req.body.cat_name+'","'+req.body.cat_desc+'","'+tt+'","'+status+'")',function(err, results, fields) {
//if (err) throw err;
if (err){
console.log("DB Error"+err);
res.send("add cate_tbl failed"+err);
}else {
generateQuery = function(data,tableName){
var fields = Object.keys(data);
var values = [];
for(var o in data) {
values.push(data[o]);
}
return "Insert into "+tableName+"("+fields.join("cat_it_id,cat_it_name,cat_pid,cat_it_count,cat_it_desc,cat_it_status")+") values ("+values.join("'"+it_id+"','"+req.body.item_name+"','"+uqid+"','"+req.body.tem_count+"','"+req.body.item_desc+"','"+status+"'")+")"
}
var query = generateQuery(req.body,"cate_item");
myconnection.query(query,function(err, results, fields) {
//your logic.
if(err)
{
console.log(err);
}
else
{
res.end(JSON.stringify(fields));
}
});
}
});
});
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
})

node js server: issue passing a variable to a function

I am building my first node.js server to perform a mysql query and return results from the database. Everything works but now I cannot find the right way to pass a value from the url (query section) to the function that performs the query (the PollingLoop function). No problems to retrieve the url and to get the parameter in the handler function but to move it to pollingLoop I have tried almost all I know about javascript (not enough I see). This is my code now that fails to run because of the reference error in pollingLoop for hwkey that is not defined.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url'),
fs = require('fs'),
mysql = require('mysql'),
connectionsArray = [],
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'flipper',
database: 'oclock',
port: 3306
}),
POLLING_INTERVAL = 3000,
pollingTimer;
// If there is an error connecting to the database
connection.connect(function(err) {
// connected! (unless `err` is set)
if (err) {
console.log(err);
}
});
// creating the server ( localhost:8000 )
app.listen(8000);
function handler(req, res) {
console.log("INCOMING REQUEST: "+req.method+" "+req.url);
req.parsed_url = url.parse(req.url, true);
var getp = req.parsed_url.query;
var hwkey = getp.hk;
console.log(hwkey);
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
}
function pollingLoop(){
// Doing the database query
var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs WHERE hwk="'+hwkey+'"'),
//var query = connection.query('SELECT max(id), testo, created_by FROM flashmsgs'),
flashmsgs = []; // this array will contain the result of our db query
// setting the query listeners
query
.on('error', function(err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);
})
.on('result', function(flashmsg) {
// it fills our array looping on each user row inside the db
flashmsgs.push(flashmsg);
})
.on('end', function() {
// loop on itself only if there are sockets still connected
if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
updateSockets({
flashmsgs: flashmsgs
});
} else {
console.log('The server timer was stopped because there are no more socket connections on the app')
}
});
};
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
console.log('Number of connections:' + connectionsArray.length);
// starting the loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}
socket.on('disconnect', function() {
var socketIndex = connectionsArray.indexOf(socket);
console.log('socketID = %s got disconnected', socketIndex);
if (~socketIndex) {
connectionsArray.splice(socketIndex, 1);
}
});
console.log('A new socket is connected!');
connectionsArray.push(socket);
});
var updateSockets = function(data) {
// adding the time of the last update
data.time = new Date();
console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
// sending new data to all the sockets connected
connectionsArray.forEach(function(tmpSocket) {
tmpSocket.volatile.emit('notification', data);
});
};
console.log('Please use your browser to navigate to http://localhost:8000');
just bring on hwkey variable out from handler
var hwkey;
function handler(req, res) { hwkey = ... }
pollingLoop(){console.log(hwkey);}

Categories