Migrating MongoDB Auth code to Mysql Node.Js - mysql

I am trying to achieve Oauth2 authentication and I came across a GitHub Repo which fits my description but the database used is MongoDB and I want to use MySql.
I want to convert this code of MongoDB Authentication to MySQL
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/MyDatabase');
const Schema = mongoose.Schema;
const UserDetail = new Schema({
username: String,
password: String
});
const UserDetails = mongoose.model('userInfo', UserDetail, 'userInfo');
I have written this much code till now
var mysql = require('mysql');
var connection = mysql.createConnection({
supportBigNumbers: true,
bigNumberStrings: true,
host : "localhost",
user : "root",
password : "root",
database : "db_users"
});
Please refer the following GitHub repo for full code
https://github.com/sitepoint-editors/LocalPassportAuth
What should I add in this code to make it work?

I had great success answering this question using the following NPM package
https://github.com/aponica/mysqlgoose-js
It saved me allot of time migrating my NodeJS authentication API's to using MySQL as my back-end database instead of using MongoDB after my free mLabs account was deactivated and MongoDB was forcing me to a paid plan.
The steps for me were
Create all MySql tables using my MongoDb models as a template
Create a mysql.json connection file allowing a connection from NodeJS to MySql
Use the NPX Import tool to create a definitions JSON file of my MySQL schema that I load at runtime in NodeJS
Build a promise-based initialization function in my routes that connects with MySql and loads the defs tile to perform mongoose-like operations on my MySql tables
Make sure to close the MySQL connection upon sending a response from my API

I recommend you to add the connection in a separate file.
After this what are your main issue ? Because the mysql code is correct for a connection.
With connection.connect() it's now working.

Related

How to connect an Azure App services to Azure Database for MySQL Flexible Server

I am working on an Azure app services in conjunction with a flexible mysql database server. I have successfully deployed my website to NodeJS v18.LTS, but my server is Throwing: SequelizeHostNotFoundError: getaddrinfo ENOTFOUND mynameserver.mysql.database.azure.com in my app services log stream. In the following question I find a possible solution by adding the ip address of the connecting host to my database instance instead of a FQDN https://stackoverflow.com/questions/25521755/errorerror-getaddrinfo-enotfound-mysql.
However, this configuration is completely discouraged.
https://techcommunity.microsoft.com/t5/azure-database-for-postgresql/dns-configuration-patterns-for-azure-database-for-postgresql/ba-p/2560287
How can I correctly set up my Flexible Server for MySQL instance to work in my production App Services environment without violating this policy?
this is my connection instance configuration:
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.USER,
process.env.MySQLPASSWORD,
{
host: process.env.HOST, // String conection xxxx.mysql.database.azure.com
dialect: process.env.dialect,
});
here I have an alternate approach of connecting to azure MySQL flexible server where I have used mysql2 npm package.
now here I am directly hard coding config data in the code, but you can easily read the application setting using same way you have used before just make sure that you first reading the respective setting for e.g.: username in a variable and then add that variable while configuring the connection to MySQL .
var username = process.env.USER
Here we use the create connection function to connect to the MySQL database and then use the query function to runa query .
The below is code form an express api:
app.use('/', (req,res)=>{
const mysql = require('mysql2');
const connection = mysql.createConnection({
host:'',
user:'',
database:'',
password:'',
port:'',
});
connection.query("CREATE TABLE TESTTABLE ( TEST int)",(err)=>{
console.log(err);
});
res.send("Hello World");
});
Here I have connected the database to MySQL Workbench where I created the table using the above code.
Here in the server I have disabled the ssl mandate

Google Cloud SQL connection in NodeJS app (Express) --> Error: connect ENOENT

I'm trying to deploy my NodeJS app on Google Cloud services and getting the following error hen I try to call a database query using Postman through localhost/8080, which is where my server is listening: connect ENOENT /cloudsql/<MY_CONNECTION_NAME>. Here's my database connection file, config.js:
const mysql = require('mysql');
const dotenv = require('dotenv');
dotenv.config();
const {
DB_PASS,
DB_USER,
DB_NAME,
} = process.env;
const config = {
user: DB_USER,
password: DB_PASS,
database: DB_NAME,
socketPath: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
};
const connection = mysql.createConnection(config);
// create connection
connection.connect((err) => {
if (err) throw err;
console.log(`Connected to database ${DB_NAME}`);
});
module.exports.connection = connection;
I know that Google recommends using a pool to connect, but I'm afraid that doing that will require me rewriting all my database queries, and I'm on a tight deadline.
I've been able to successfully shell into the database with MYSQL using the terminal.
Take a look at the Connecting to App Engine page. In particular, here are some things you should check if the socket isn't present:
For GAE Flex, make sure you have the following in your app.yaml:
beta_settings:
cloud_sql_instances: <INSTANCE_CONNECTION_NAME>
Ensure the SQL Admin API is enabled and make sure you have the correct IAM permissions (Cloud SQL Client1 or higher) on your service account (service-PROJECT_NUMBER#gae-api-prod.google.com.iam.gserviceaccount.com`). If between projects, make sure you have the
Make sure you are spelling <INSTANCE_CONNECTION_NAME> correctly. It should be in the format <PROJECT>:<REGION>:<INSTANCE> - you can copy it exactly from the "Instance Details" page for your instance.
Additionally, using a connection pool will have no effect on your queries. Using a pool only means that when you "open" a connection, it is actually reusing an existing connection, and when you "close" a connection it puts it back in the pool for your application to use elsewhere. The queries you perform using the pool should be exactly the same.
this is happen if you are using flex as env in app.yaml to run without errors remove the env:flex from your app.yaml,
your app.yaml need to look like this
app.yaml
and you will successfully connected to the cloud sql without causing errors
console log

How to use singleton design pattern with mysql connection and pooling in node.js

I'm using node-mysql as the orm. (https://github.com/mysqljs/mysql)
I'm creating a REST API using MySQL and Node.JS. Earlier I did the same using MongoDB. And it's working fine. github.com/chanakaDe/Mint-REST. Now I want to do the same using MySQL. I did most of the part and having a little issue. There are many classes and I need to use mysql connection in a centralized way. As singleton design pattern.
This is the my new repo. https://github.com/chanakaDe/MintRestSQL. And I will show where I want to use those patterns. Here I have the database file. And I created a new connection pool. github.com/chanakaDe/MintRestSQL/blob/master/app/util/database.js.
Now I want to use this connection/pool inside my controller classes. Because I cannot create a connection in each and every controller class. No ? These are my two controllers for now.
github.com/chanakaDe/MintRestSQL/blob/master/app/routes/report.js
github.com/chanakaDe/MintRestSQL/blob/master/app/routes/api.js
Please show me a better way to do this. I am new to node-mysql. But it's a great way to use MySQL inside Node.JS environments even for production grade systems. So I want to make a good API using those standards. Is there any way to use singleton pattern or something like that and centralized the connection and use it in all the controllers ????
IT WILL TAKE SOME TIME TO CHECK MY FILES AND UNDERSTAND THE CODE. BUT PLEASE CHECK IT AND GIVE ME A SOLUTION. I TRIED MANY THINGS, BUT DIDN'T WORK :(
You are welcome to pull the repo and make any update
Try change database.js to
var mysql = require('mysql');
mysql.createPool({
host : 'localhost',
user : 'root',
password : 'chanaka',
database : 'shared_adult'
}).connect();
module.exports = mysql;
To offer an alternative to anyone arriving here (like me) that needed to inject a dependency (i.e. the credentials). Below is the approach that will yield a runtime confiurable singleton:
var mysql = require('mysql'),
db;
module.exports = {
init: function(conf){
if(!db){
db = mysql.createPool({
host: conf.host,
user: conf.root,
password: conf.password,
database: conf.database
});
}
},
get: function() {
if(!db) {
throw new Error('The db pool has not been initialized, call init({}) prior to get().');
}
return db;
}
};
//initialize where you access your config (which should theoretically only be one place)
var mysqlDb = require('db'); //path to above db module
mysqlDb.init({
host: 'host',
user: 'user',
password: 'password',
database: 'database'
});
//use in your modules
var mysqlDb = require('db'), //path to above db module
db = mysqlDb.get();

Using node.js, express, and MySQL

I am currently in the process of creating an app and I am using node.js, express, and MySQL. I feel that I am in a bit of a rut in connecting my server to my database. Here's how I see things so far
server.js
var express = require('express');
var app = express();
//These are just my static finals so this can be ignored for now
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use(express.static(__dirname + '/public/controlers'));
app.listen(3000);
console.log("Listening at 3000")
Here I am setting up a local server on my computer that is listening on port 3000. What I am hoping to do here eventually is handle post requests. My goal is to ensure that post requests are inserted into the database. So I realize that I need to do two things create a database and a schema for my database. For now I just want to create a simple table with an ID and first_name columns. I am using this driver https://github.com/felixge/node-mysql/.
So my next step is creating a connection
dbconnection.js
var mysql = require('mysql')
var app = require('../server.js');
var connection = mysql.createConnection({
host : 'localhost',
port : 3000,
user : 'username',
password : 'password',
database : 'liveDatabase'
});
connection.connect()
//queries and error handling go here
connection.end()
This is where I lose touch with my program.
Here's what I don't understand:
I don't get how a connection is being created to my localhost:3000. I see the key values for host and post being assigned to localhost and 3000 and I am requiring my server in the db.js file (var app = require('../server.js');. Is this all that is needed to create a connection? How does it find localhost:3000? I am guessing this is all happening under the hood, but I feel a little stuck here.
I have confusion about the database as well. Where should my database be created and live in order for .createConnection to be able to find it. Do I create a separate .sql file then just create my database and table(s) there and require(/database/path) in my dbconnection.js?
Any help is appreciated. Thanks!
This is just a start, but this seems to be the crux of the misunderstanding:
Your server.js is creating a web server that listens on port 3000. Your dbconnection.js is trying to connect on that server on port 3000. That's not right. You want it to connect to your MySQL server instead.
It seems more logical for server.js to require dbconnection.js rather than the other way around. Then server.js can send/receive info with the database via the required module.

Mysql changes listener for node.js

Is there a way that mysql server in node.js listens for changes in the database and get a callback for that changes like Database Changes Notification in Oracle DB?
I'm thinking to implement it somewhat like this way
var mongo = require("mysql");
var client = require('socket.io').listen(port).sockets;
var db = mysql.createConnection({host: host, user: user, database: db});
db.listen.on('changes',function(){
client.emit("hasChanges");
});
You can try, the mysql-events package for NodeJS.
But before you try:
Make sure the database user has the privilege to read the binlog on database that you want to watch on.