NodeJs With Mysql createPool and nodejs mysql wrapper module - javascript

i am using nodejs with mysql createPool and node-mysql-wrapper.
Link:
https://www.npmjs.com/package/node-mysql-wrapper
There is no option in the documentation to implement with module with myslq create pool. I tried it, but its not working. Here is my code:
var connection = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: '',
database: 'test'
});
var db = wrapper.wrap(connection);
db.ready(function(){
db.table("users").findById(8,function(user){
console.log(user);
});
});

As #Tajen Shrestha said. You need bind the wrapper with connection object. For e.g.:
var conObj = connection.getConnection.bind(connection);
var db = wrapper.wrap(conObj);
db.ready(function(){
db.table("users").findById(8,function(user){
console.log(user);
});
});

Related

Node.js MySQL Connection Error. ECONNREFUSED

I have 2 servers, one running the frontend code (Node.js, express) and the other running MySQL with PHPMyAdmin, both are working standalone and I can confirm the MySQL database is running on 3306 but whenever I try to connect via Node.js (code below) I get a connection refused error.
const conn = mysql.createConnection({
host: '192.168.1.250',
user: 'mcd',
password: '**********',
database: 'mcd'
})
conn.connect(function(err) {
if (err) throw err;
})
The IP address I have used for the host is the IP address of the MySQL server. So unsure why it cannot connect since it is running on the default port.
Here is my connection to Node.js:
pool = mysql.createPool({host:"localhost"
,port:"3306"
,database:"db_name"
,user:"user_name"
,password:"password_for_user"
,timezone:"utc"
,multipleStatements:true
,max:1000
,min:1
,idleTimeoutMillis:defs.QUERY_TIMEOUT});
if ( pool && pool.getConnection ) {
pool.getConnection(function(errsts, conn) {
var resp = {};
if ( errsts ) {
resp['error'] = errsts;
return;
}
resp['state'] = "connected";
if ( cbRoutine ) {
cbRoutine(conn, resp, objParams);
if ( conn != undefined ) {
conn.release();
}
}
});
}
localhost is correct for my usage, you should replace its your name or IP address.
defs.QUERY_TIMEOUT is defined in my source as:
var QUERY_TIMEOUT = 10 * 1000;
In my code cbRoutine is a call back function passed in as a parameter to call on successful connection.
The ECONNREFUSED error indicates that it can't connect to where the function is hosted (in this case localhost)
dbConnection.js
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10, // default = 10
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dname'
});
module.exports = connection;

Error Connecting to the database: Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server

I've tried following the suggestion at this link: MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
and am aware that it is using cahcing_sha2_password instead of mysql_native. However, I've tried following the suggestions and am still receiving the same errors, trying to connect to the database with node.
Schema name: 'my_db'
//DATABASE CONNECTION SETTINGS
const APIServerPort = 3001;
const database = {
host: "localhost",
port: 3306,
user: "root",
password: "xxx",
database: "my_db"
};
module.exports = {
database,
APIServerPort
};
app.js file:
const express = require("express");
const app = express();
const router = express.Router();
const settings = require("./settings");
const routes = require("./routes");
const mysql = require("mysql");
const connection = mysql.createConnection(settings.database);
router.get("/employees", routes.employees.listAllEmployees);
app.use("/apis", router);
connection.connect(error => {
if (error) {
console.error("Error Connecting to the database: " + error);
return process.exit();
}
app.listen(settings.APIServerPort, () =>
console.info(`Server is running at port ${settings.APIServerPort}...`)
);
});
SQL Queries Ran:
CREATE USER 'root'#'localhost:3301/apis/employees' IDENTIFIED WITH mysql_native_password BY 'xxx';
FLUSH PRIVILEGES;
I'm still receiving the same error however.
mysql users are in the form 'root'#'localhost'. Urls are a node.js concept only.
As that user already exists create a new one:
CREATE USER myapplication#localhost
IDENTIFIED WITH mysql_native_password BY 'xxx';
GRANT ALL ON my_db.* TO myapplication#localhost`;
You don't need FLUSH PRIVILEGES.

Javascript class method returning undefined

I'm trying to return a value from a class but it's coming up undefined.
index.js
import DB from "./db.js"
import express from "express";
import cors from "cors";
const database = new DB();
app.get("/", (req, res) => {
const data = database.selectAllFromProducts();
console.log(data); // Returns undefined
});
app.listen(process.env.PORT, () =>
console.log(`Listening on Port ${process.env.PORT}`)
);
db.js
class DB {
constructor() {
this.connection = this.initialize();
}
initialize() {
return mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
selectAllFromProducts() {
this.initialize();
this.connection.query(`select * from ${process.env.DB_PRODUCTS_TABLE};`,
(err, results, fields) => {return results});
}
}
I have a front end that is sending the GET request and that is successful so it's not a routing problem. Console.logging the results works from db.js so I know it's not a MYSQL problem but for whatever reason it comes up blank in index.js. Thanks in advance for any help!
EDIT - I have module.exports = DB I just forgot to include it because I only included partial bits of the file. Importing works just fine for me because I'm using babel and type: module in my package.json. I couldn't tag node because it requires 1500 rep.
You forgot to export your module. Thus database should be undefined in your code, resulting in your issues.
class DB {
constructor() {
this.connection = this.initialize();
}
initialize() {
return mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
selectAllFromProducts() {
this.initialize();
this.connection.query(`select * from ${process.env.DB_PRODUCTS_TABLE};`,
(err, results, fields) => {return results});
}
}
module.exports = DB;
Also importing is a little different in node.js
var DB = require("./db.js");
var express = require("express");
var cors = require("cors");
const database = new DB();
app.get("/", (req, res) => {
const data = database.selectAllFromProducts();
console.log(data); // Returns undefined
});
app.listen(process.env.PORT, () =>
console.log(`Listening on Port ${process.env.PORT}`)
);
Note: You should be able to use javascript modules in node.js versions greater than 13 (which is why your code may be working). Make sure your deployment server supports node.js 13 as well if you decide to use that syntax. More on javascript modules

Having an issue with createClient

Okay, so how my code works is that a discord bot in the index.js file has stored usernames and passwords.
When I make a request to the minecraft file, using minecraft-protocol i create a login to a server called Client,
clientName = mc.createClient({ // connect to 2b2t
host: "2b2t.org",
port: 25565,
username: username,
password: password,
version: "1.12.2"
});
an issue with this is, when a new user (while the current client is still going) trys to create a client, the old one is dropped for the new one. I need a way to identify one from the other.
You are more than likely overwriting the original connection, causing it to drop. You could instead make a connection factory and be able to create many connections.
class ClientFactory {
constructor(mc) {
this.mc = mc;
this.clients = {};
}
create(key, options) {
const client = this.mc.createClient(options);
this.clients[key] = client;
return client;
}
get(key) {
return this.clients[key];
}
}
// Instantiate factory
const client = new ClientFactory(mc);
// Make first client
client1 = client.create('client1', {
host: "2b2t.org",
port: 25565,
username: username,
password: password,
version: "1.12.2"
});
// Make second client
client2 = client.create('client2', {
host: "2b2t.org",
port: 25565,
username: username,
password: password,
version: "1.12.2"
});
// Do something with one of them
client.get('client1').callSomething();

How can I keep a constant MySQL connection alive in NodeJS

I'm currently developing Discord Bot, for data storing I'm using MySQL, but after some hours de connection dies. I was wondering if someone has a clue on how to do this. This the way I currently connect:
// Initalise Variables
var config;
var mysql, conn;
var fs;
try {
// External Packages
fs = require('fs');
config = require('./config.json');
mysql = require('mysql');
// Connection Setup
conn = mysql.createConnection({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
conn.connect();
} catch (e) {
console.error(e);
}
You can try changing the timeout setting else if would default to 10000ms or 10 seconds.
try {
// External Packages
fs = require('fs');
config = require('./config.json');
mysql = require('mysql');
// Connection Setup
conn = mysql.createConnection({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database,
connectTimeout: config.mysql.timeout //1000000 some large number
});
conn.connect();
} catch (e) {
console.error(e);
}
You should probably use a connection pool instead of a single DB connection (this doesn't seem to have always keep alive type of setting, and you would have to give a large timeout like above)
try {
// External Packages
fs = require('fs');
config = require('./config.json');
mysql = require('mysql');
// Connection Setup
conn = mysql.createConnection({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database,
connectionLimit: 10,
queueLimit: 20
});
var pool = mysql.createPool(config);
var queryDB = function(qry, cb) {
pool.getConnection(function(error, connection) {
if(error) {
cb(error, null);
}
else {
connection.query(qry, function (e, rows) {
connection.destroy();
cb(e, rows);
});
}
});
I think you need to install forever and start the service again. Forever is a simple CLI tool for ensuring that a given script runs continuously. Once you install forever and run the node js file then it will keeps the file alive continuously. Using npm you can install forever
npm install forever -g
Then just restart the js file
Ex:
forever start app.js
Hope now the js serves continously without breaking the connection.

Categories