acess function in objected, nested inside another function - javascript

Im trying to manage a connection instance, using a function to handle idle connection disconnect issues, using mysql database and node.js
At moment, i've got following code (coffescript):
mysql = require 'mysql'
handleDisconnect = () ->
connection = mysql.createConnection
host: 'localhost'
user: 'root'
password: 'passroot'
database: 'mydb'
connection.connect (err) ->
if err
console.log 'Error connecting to db: ', err
setTimeout handleDisconnect, 2000
connection.on 'error', (err) ->
console.log 'db error', err
if err.code == 'PROTOCOL_CONNECTION_LOST'
handleDisconnect()
else
throw err
handleDisconnect.instance = connection
module.exports = handleDisconnect
and
express = require 'express'
router = express.Router()
connection = require('../database')().instance
bcrypt = require 'bcryptjs'
router.post '/', (req, res) ->
credential = connection.escape req.body.credential
password = connection.escape req.body.password
res.send credential+password
module.exports = router
Problem is, when i try to access the route, i get following error:
Cannot read property 'escape' of undefined
What am i doing wrong?

I believe your issue is that the final line of handleDisconnect is returning the instance, so you're trying to get the instance from instance, not from handleDisconnect. So you'll need the function to return itself at the end if you want to access properties on it.
You also want the function to be using the equivalent of "this" (# in coffeescript) rather than specifically referring to handleDisconnect.
Example code:
mysql = require 'mysql'
handleDisconnect = () ->
connection = mysql.createConnection
host: 'localhost'
user: 'root'
password: 'passroot'
database: 'mydb'
connection.connect (err) ->
if err
console.log 'Error connecting to db: ', err
setTimeout handleDisconnect, 2000
connection.on 'error', (err) ->
console.log 'db error', err
if err.code == 'PROTOCOL_CONNECTION_LOST'
handleDisconnect()
else
throw err
#instance = connection
#
module.exports = handleDisconnect
Although I'd personally just do the following, don't bother with "instance" at all:
Use #connection in your function
Scrap the #instance = connection
Get the function to return itself
Access it with require('../database')().connection.

Related

Trying to build lambda function using SAM plugin in visual studio code and trying to connect to MYSQL RDS instance but not working

I am building lambda function using visual studio code SAM option. I am trying to connect to RDS instance (MYSQL) which is in VPC network.
I tried connecting using following code. I am not getting any error but it is not connecting to DB. I have searched every where but didn't get any solution. I tried following but didn't worked
const fs = require('fs');
const mysqlssh = require('mysql-ssh');
mysqlssh.connect(
{
host: 'XXX.XXX.XX.XX',
user: 'ec2-user',
privateKey: fs.readFileSync('./XXXX-txlarge.pem')
},
{
host: '-staging-instanceXXXXX.rds.amazonaws.com',
user: 'user',
password: 'password',
database: 'db'
}
)
.then(client => {
client.query('SELECT * FROM users', function (err, results, fields) {
if (err) throw err
console.log(results);
mysqlssh.close()
})
})
Instead of using mysql-ssh which is tunneling based type of sql connection module try to use simple mysql module,
const fs = require('fs');
const mysql = require('mysql');
let connection = mysql.createConnection(
{
host: 'XXX.XXX.XX.XX-staging-instanceXXXXX.rds.amazonaws.com',
user: 'user',
password: 'password',
database: 'db'
}
);
connection.connect();
connection.query('SELECT * FROM users', function (err, results, fields) {
if (err) throw err
console.log("rows: " + rows);
context.succeed('Success');
});
PS: You might need to some of code as per you needs, but this is what you should try doing.

JS variable scope within Hapi JS route handler

I ran into a mysql connection error which I seem to have fixed by guessing it was a JS variable scope issue.
In the route handler I've commented out the code that was throwing the following MySQL error: PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR, and included the working code below.
require('dotenv').config();
const Hapi = require('hapi');
const mysql = require('mysql');
const Joi = require('joi');
const query = require('./lib/mysql/query');
const server = new Hapi.Server();
server.connection({
host: process.env.SERVER_HOST,
port: process.env.SERVER_PORT
});
const dbOne = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER_ONE,
password: process.env.DB_PASSWORD_ONE
});
const dbTwo = mysql.createConnection({
host: process.env.DB_HOST_TEST,
user: process.env.DB_USER_TWO,
password: process.env.DB_PASSWORD_TWO,
});
server.route({
method: 'GET',
path:'/my-route',
config: {
validate: {
query: {
useDatabase2: Joi.valid('true'),
},
},
},
handler: (req, reply) => {
const useDatabase2 = req.query.useDatabase2 === 'true';
// This didn't work...
/*
const db = useDatabase2 ? dbTwo : dbOne;
db.query(query, (err, rows) => {
if (err) {
reply({
statusCode: 500,
error: "Internal Server Error",
message: err,
}).code(500);
} else {
// ...do something with the data
}
});
*/
// This works...
if (useDatabase2) {
dbTwo.query(query, (err, rows) => {
if (err) {
reply({
statusCode: 500,
error: "Internal Server Error",
message: err,
}).code(500);
} else {
// ...do something with the data
}
});
} else {
dbOne.query(query, (err, rows) => {
if (err) {
reply({
statusCode: 500,
error: "Internal Server Error",
message: err,
}).code(500);
} else {
// ...do something with the data
}
});
}
}
});
server.start(err => {
if (err) throw err;
});
I had assumed that const db was just a reference to the original variable (dbOne or dbTwo) within it's own scope and ceased to exist at the end of each request.
Is the db variable really conflicting with itself and causing the MySQL connection to fail!?
You might wanna look at this thread, which talks about variable reassignment for mysql connections -
https://github.com/mysqljs/mysql/issues/900
Also as a precaution, try adding the 'use strict' directive to your js files. It will help avoid the conflict of variables in your entire application
Finally got to the bottom of this. The variable scope wasn't the issue.
Something was causing the MySQL connection to fail (perhaps the database server's network or load), and as I wasn't pooling the connections, once a connection broke it stayed broke.
I switched mysql.createConnection({... to mysql.createPool({... so when one connection failed another replaced it, and so far so good.

Unable to connect MySQL DB, getting ECONNREFUSED

I tried to connect the DB via MySQL Java Script as below:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "******",
user: "******",
password: "******"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
And I'm using Node to execute, While I execute the above program getting the below error message:
if (err) throw err;
^
Error: connect ECONNREFUSED XX.XXX.XX.XXX:3306
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
Also I have pinged my ip address (ping XX.XXX.XX.XXX) and can able to get the response. Can help me to connect the DB.
I had the same issue and the error resolved by adding the socketPath parameter
var connection = mysql.createConnection({
user: 'user',
password: 'pass',
socketPath: '/var/run/mysqld/mysqld.sock',
database: 'dbname'
});
I highly suggest creating a connectionPool to save your resources. Here is how I did it:
//import settings.js
const db_config = {
hostname : "localhost",
user : settings.user, //username
password : settings.password, //password
database : settings.database //db
}
//create db connection pool
const con = mysql.createPool(db_config);
So the next step is to use that connection pool! Don't be scared about the async/bluebird nature of this code, it's just how I built it.
async function query(sql, params) {
const connection = await con.getConnectionAsync();
return connection.queryAsync(sql,params)
.then(rows => rows)
.finally(() => connection.release());
}
This is grabbing the connection getConnection method (Async is from bluebird promisifying the method), and using the query method (async'd), and then finally releasing the connection back into the pool. This helps save you from memory leaks caused by unclosed TCP connections.
Make sure that you also specify the port if you have changed it from the default MySQL port as well.

Node js mysql query gives error when executed second time

I am trying to make a REST api in node using express. When i open the url in browser the first time, it runs fine and gives me the correct output. But when I hit the api url the second time, the app crashes with the error :
events.js:141
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after invoking quit.
This is the code I'm using :
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'USER_NAME',
password: 'PASSWORD'
});
app.use(express.static(__dirname + '/public'));
var port = 3333;
app.get('/api/users/:user_id', function(req, res){
var lead_id = req.params.user_id;
connection.connect();
connection.query('use DB_NAME;', function (err) {
if(err) throw err;
connection.query('select * from users where user_id = ' + user_id, function (err, rows) {
if(err) throw err;
res.json(rows);
connection.end();
});
});
});
app.listen(port);
console.log("The app is running on port " + port);
Can someone tell me what am I doing wrong ?
Just remove connection.connect() and connection.end(). Then it should work.
connection.connect() should be called once or none. Because connection.query will connect I'd it not connected.
PS - connection.connect() need to be called when the connection is lost.
Try this to remove the redudant connection. This was the first result of a google search of the error message - always try to google error messages before asking SO.

NodeJS/MongoDB - Clone Collection with Indexs

I'm trying to clone a mongodb collection with the indexs from two different MongoDB instances. After googling around, I found that cloneCollection would be my best bet. I've tried to make my code nice and simple, but I never seem to get the actual clone command to run. 'Started' and 'Authed' pop up in my console, but the command never runs. What is it I'm doing wrong? Thanks.
mongodb = require("mongodb")
#####################
# MONGODB CONFIG
#####################
console.log "Started"
Server = mongodb.Server
Db = mongodb.Db
server = new Server("example.com", 27017, {})
db = new Db("databaseTwo", server,
safe: true
)
db.open (err, db) ->
db.authenticate "user", "password", (err, res) ->
throw err if err
console.log "Authed"
db.command
cloneCollection: "databaseOne.helloThereCollection"
from: "example.com:6001"
key:
username: 'user'
password: 'password'
, (err, cb) ->
console.log err if err
console.log 'Command Ran'
cb null

Categories

Resources