How to access mysql database with socket.io - mysql

I'm just getting into coding server side javascript and have been reading tutorials on socket.io and node.js, but I haven't come across anything demonstrating how to use node.js to access a mysql database.
Say for instance I want to create a method that listens to a table in my database at
mysql.something.com (with database: database, username: username, etc), how would
I get socket.io with node.js to connect to that database and listen for new input to that table and then subsequently return that input?
I'm wondering if anyone could give me a specific example that uses a publish subscribe model.
Thanks for the help.

You have to poll mysql database for changes at regular interval and when detect a change emit a socket.io event. Here's a pseudo code
var mysql = require('mysql');
var connect = mysql.createConnection({
host: 'localhost'
, database: 'your_database'
, username: 'user'
, password: 'password'});
var initial_result;
// check for changes after 1 second
setTimeout(function(){
connect.query('select * from your_table', function(err, result) {
if(err) { throw new Error('Failed');}
initial_result = initial_result || result;
if(Changed(initial_result, result)) { socket.emit('changed', result); }
});
function Changed(pre, now) {
// return true if pre != now
}
}, 1000);

Related

is it possible to connect to mysql database directly without rest api?

I'm very new to this backend stuff but I really want to know or else I can't sleep tonight or many other nightss.......
I'm tasked to build a rest API that will allow our web application to update our company's MySQL database remotely from any internet or client.
basically, the web application will be built using react framework that will allow users to take in some inputs and send them to the backend and update the MySQL database remotely.
so far, I have the rest API ready and inside this rest API i have included some mysql methods that will update the table in our database. it works fine.
but suddenly I couldn't find the reason why we need the rest API in the first place
below is the code I have...my question is
can't we just skip the express part? and directly connect the application to MySQL database using the mysql methods createConnection and then run db.query(sqlInsert) without running the app.get?
the only reason I can think of is that, if I do this, it will probably allow anyone to access the database from the browser's console. In this case, does it mean rest API is just like a filter that simply runs a server site after the user clicks the submit button, and then once the server runs it will then take the submitted information and run the db.query()? and then once that is complete, it will send back a response displayed on the server site saying its working?
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createConnection({
host:'the ip address of the computer that has the mySQL database',
user: 'the user name created in workbench',
password: 'the password created in workbench',
database: 'the database name',
port: '1234'
})
db.connect(function(err){
if(err){
console.log(err)
process.exit(1)
}
console.log("connected to mysql")
})
app.get('/', (req,res) => {
const sqlInsert = "INSERT INTO person123 (customerid, firstname, lastname) VALUES ('USv10', 'USv10', 'USv10');"
db.query(sqlInsert), (err, result) =>{
}
res.send('working')
})
app.listen(3001, () => {
console.log ('running on port 3001 yes')
})
yes you can connect with mysql without express and running restful api but
condition is that server will be running using a specific port.with only this block
of code your server is connected to databse.
var mysql = require('mysql');
var con = mysql.createConnection({
host:'the ip address of the computer that has the mySQL database',
user: 'the user name created in workbench',
password: 'the password created in workbench',
database: 'the database name',
port: '1234'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
and this block is nesecary for running server on specific port
app.listen(3001, () => {
console.log ('running on port 3001 yes')
})

How to use Auth0's custom database to add a user to a MySQL database?

I am using Auth0 for a login service but I have a need to add a user to a database in MySQL every time an account is registered through Auth0.
They give this following script template but I am a newbie and need help debugging and understanding it. My specific questions are detailed as comments:
function create(user, callback) {
var connection = mysql({
host: 'localhost', //what should this be?
user: 'KNOWN/Understood',
password: 'KNOWN/Understood',
database: 'KNOWN/Understood'
});
connection.connect();
var query = "INSERT INTO users SET ?"; //what does this do?
bcrypt.hash(user.password, 10, function (err, hash) { //what does this do?
if (err) { return callback(err); }
var insert = {
password: hash,
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
});
}
Is there anything else I need to change for this script or understand or call in for it to work?
I often get the error missing username for Database connection with requires_username enabled and I'm unsure what this means.
I'm assuming you already went through this tutorial on custom databases so let's address your specific questions.
host: 'localhost' // What should this be?
This and the other properties of this object define the way to connect to your custom MySQL database. The database needs to be reached from within Auth0 servers so this needs to be a host name accessible from the Internet.
"INSERT INTO users SET ?"; // What does this do?
This defines an SQL insert command that uses ? as a placeholder for later substitution.
If you see where this query is later used, you will noticed it's invoked with an additional insert object parameter that will cause the above query to be expanded into something like:
INSERT INTO users SET email = 'user#example.com', password = 'asdf34ASws'
bcrypt.hash(user.password, 10, function (err, hash) // What does this do?
This hashes the user provided password so that it's not stored in plain text in the database.
If you chose to require a username in addition to email you need to address this in your custom scripts as I believe the default templates assume that only email will be used.
This means that when creating the user in your database you also need to store the username and in the script to verify a user you also need to return the username.

Connecting to RDS database from node.js

I am trying to learn node.js so that I can actually get started on working on my personal project. I have been trying to follow the examples in the book "Learning node.js" (by Marc Wandschneider). I, at this point, decided to forgo practicing his example, and go straight into using his code as framework for my practice code.
In my practice code, all I am trying to do is connect to my RDS database (no, I am not using Elastic Beanstalk, btw), and output contents of one of the tables. Seems simple enough, but when I whip up the code for it (based on the book), it seems to attempt connection, but get hung up in the process. This is my code:
var pool = require('generic-pool');
var async = require('async');
var mysql = require('mysql');
var host = "<database-name>.cu8hvhstcity.us-west-2.rds.amazonaws.com",
database = "<database-name>",
user = "<username>",
password = "<someLongPassword>";
var dbClient;
async.waterfall([
// 1. establish connection to database
function (callback) {
console.log("Connecting to database " + database + "...");
dbClient = mysql.createConnection({
host: host,
database: database,
user: user,
password: password,
port: 3306
});
dbClient.connect();
},
// 2. select all from a table (let's go for locations)
function (cb)
{
var query = "SELECT * FROM locations"
console.log("running query \"" + query + "\"...");
dbClient.query(query, cb);
},
function (rows, fields, callback)
{
console.log(fields);
for (var i = 0; i < rows.length; i++)
{
console.log(JSON.stringify(rows, null, '\t'));
}
}
], function (err, results) {
if (err)
{
console.log("An error occurred...");
console.log(err);
}
else
{
console.log("Everything successfully completed!");
}
dbClient.end();
})
This is better than first attempt, when I put a database member to the argument passed to mysql.createConnection(), and it complained that database was unknown. In neither case did either "An error occurred..." nor "Everything successfully completed!" output to the window.
Is there any async stuff going on that is resulting in some kind of non-terminating infinite loop or something? How do I fix this?
The book has an associated GitHub page
NOTE:
Neither my example nor the cited GitHub code make use of that pool variable, so it can simply be commented out. All you need to do to run this yourself is to say npm install async,npm install mysql (as well as creating a dummy RDS database to point to, that contains locations table) before copying, pasting, and running this code.
EDIT:
I fixed the issue with database. I realized that the name of the database used '_', not '-'. Same issue (code hangs) still persists...
I did the following:
In the second function in the array, I needed two parameters, not one.
I fixed thus:function(results, cb)
The third function simply needed to callback(null)

MySQL NodeJS Openshift server - query to database seems to not be working

I have a nodejs server in Openshift with a MySQL cartridge. It seems to build with no problem, however, when I try to query the database, it seems to be doing nothing... It doesn't even give me an error, it's just does nothing. Here's my relevant code.
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'mysql://' + process.env.OPENSHIFT_MYSQL_DB_HOST + ':' + process.env.OPENSHIFT_MYSQL_DB_PORT + '/',
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database: 'revision',
multipleStatements: true,
debug : true
});
And in the appropriate route:
var stuff = 'abc';
connection.query('SELECT 1', function(err, rows, fields){
if (err) {
stuff = "ghi";
} else {
stuff = "def";
}
});
stuff = stuff + "done";
res.send(JSON.stringify(stuff));
It should return "defdone" or "ghidone", but it always returns "abcdone"... It's like it doesn't even get inside the function. I've tried several ways of doing this and none work. I've dumped the connection variable and it seems to be what's meant to be.
The reason I'm using SELECT 1 as the query string was to verify it was not a database error.
It seems the "issue" had to do with the asynchronous nature of node, as the final 2 instructions are executed before the query is completed. Furthermore, the configs seemed to be wrong after all, as I only had a "host" attribute with the whole url. I changed it into to 2 attributes - "host and "port", giving them the appropriate variables (process.env.OPENSHIFT_MYSQL_DB_HOST and process.env.OPENSHIFT_MYSQL_DB_PORT). It's working now!

How can I begin MySQL work in Node.js on Windows?

I've begun playing around with Node.js lately, for many reasons but most importantly the ease at which I can write a chat-server utilising HTML5 WebSockets. However, I've been stuck for weeks with MySQL.
I'm currently using this MySQL client module: https://github.com/sidorares/nodejs-mysql-native
I've connected to the database and managed to store data using the following code:
// MySQL database
var db = require("mysql-native").createTCPClient(); // localhost:3306 by default
db.auto_prepare = true;
db.auth(dbName, dbUser, dbPass);
// Update the database
db.execute("UPDATE server_data SET value='" + new Date() + "' WHERE name='lastLoaded'");
How may I go about retrieving data from the database using a SELECT * FROM x WHERE y=z query?
Is there any specific reason you chose nodejs-mysql-native over node-mysql which is a really good node module. If there is none, then you should probably try node-mysql. I've tried it and it is great to start off using MySQL with Node. You could do something like:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'your_username',
password : 'your_password',
});
connection.connect();
connection.query("UPDATE server_data SET value=? WHERE name=?", [new Date(), 'lastLoaded'] function(err, result) {
if (err) throw err;
console.log('Result: ', result);
});
connection.end();
The advantage you get by using it this way is that you can prevent SQL injection, which is taken care of internally in node-mysql (by using the connection.escape() method).