Exporting Mysql Connection in nodeJS - javascript

In my database.js I have
var Mysql = require('Mysql');
var Jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
var supersecretkey = 'JMDub_Super_Secret_key';
var config = require('./config');
var signupErrors = require('./Signuperrors.js');
var sucessMsg = require('./SucessMessages.js');
var App_errors = require('./error.js');
var query = require('./queryDB.js');
var connection = Mysql.createConnection({
"host": "******",
"user": "****",
"password": "***",
"database": "***"
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
//Sign Up Methods
var createUser = function createwithCredentails(post,callback) {
bcrypt.hash(post.password, 10, function(err, hash){
//console.log('Cache Hash : +',hash);
var createUserQuery = connection.query('INSERT INTO users SET ?',{"email":post.email,"password":hash,"username":post.username},function(err,result){
if (err) {
if (err.code == 'ER_DUP_ENTRY') {
//console.log(err.code);
callback(signupErrors.error_5000);
}
else callback(App_errors.error_1003);
}
if (result) {
callback(sucessMsg.success_signup);
}
});
});
}
//connection.query('SELECT * FROM Users Where Username = '' AND Password = ''');
var validateUser = function ValidateUserWithUserNameAndPassword(post,callback) {
var UserCheckQuery = connection.query('SELECT * FROM users WHERE email="'+post.email+'"',function(err, results, fields) {
if (err){
console.log(err);
callback(App_errors.error_1000);
}
if (results.length == 1) {
//console.log(results[0].password,post.password);
var givenPassword = post.password;
var DBhash = results[0].password;
bcrypt.compare(givenPassword, DBhash,function(err, res) {
if (res) {
console.log('Password matched');
var token = Jwt.sign({"email":post.email,"username":post.username},supersecretkey, {
expiresIn: 60*60*5 // expires in 5 hours
});
callback({
message:{
"success":1,
"description":"sucessfully logged in - please cache the token for any queries in future",
"environment":"test",
"errorCode":null
},
"token":token
});
}
if (!res) {
console.log('password doesnt match');
callback(signupErrors.error_6000);
}
if (err) {
console.log('Error Comparing Passwords');
callback(App_errors.error_1004);
}
});
}
else{
callback(signupErrors.error_6000);
}
});
};
var isauthenticate = function isauthenticated(post,route,callback) {
if (post.headers.token) {
Jwt.verify(post.headers.token, supersecretkey, function(err, decoded) {
if (decoded) {
//console.log(decoded);
//From this part the user is Sucessully Authenticated and autherization params can be extracted from token if required
//Write Business Logic in future as per the requirement
//Operation 1 - Update Profile
//Profile Details consists of {1.first name 2.last name 3. profile pictur(base 64 encoded) 4.further settings in future that can be added to DB if required}
if (route == '/update-profile') {
query.updateProfile(connection,decoded.email,post.body,function(response) {
callback(response);
});
}
//callback({"message":"is a valid token"});
}
if (decoded == null) {
console.log('is not a valid token');
//callback(App_errors.error_1000);
}
if (err) {
console.log('error verifying token');
callback(App_errors.error_1000);
}
});
}
else{
callback(App_errors.error_1001);
}
};
module.exports = {
validateUser:validateUser,
createUser:createUser,
isauthenticate:isauthenticate,
connection:connection
}
I am exporting connection object to queryDB.js file. But when I try to log the exported connection object I get undefined object. Why is this happening?
When I pass connection object as function argument, everything works fine. Not sure why?
below is queryDB.js file
var errors = require('./error.js')
var Dbconnection = require('./Database.js').connection;
var updateProfile = function profiledata(connection,email,data,callback) {
console.log(Dbconnection);
if ((!data)|| (Object.keys(data).length < 1)) {
//console.log(data);
callback(errors.error_1001);
}
else{
callback({"message":"update Sucesss"});
//console.log(connection);
//var updateData = mapProfileDataTomodel(data);
//console.log(updateData);
connection.query('SELECT * FROM users WHERE email = "'+email+'"',function(err, result,feilds) {
if (err) throw err;
if (result) {
console.log(result);
}
});
}
}
var mapProfileDataTomodel = function mapProfileDataTomodel(data) {
var profileDataModel = {};
for (var key in data) {
//console.log('looping and mapping data');
if (data.firstname) {
profileDataModel.firstname = data.firstname;
}
if (data.lastname) {
profileDataModel.lastname = data.lastname;
}
if (data.profilepic) {
profileDataModel.profilepic = data.profilepic;
}
}
return profileDataModel;
}
module.exports = {
updateProfile:updateProfile
}
I have commented out connection object log via function arguments.
So, Why I am unable to get the connection object that is exported? But I used the same exported connection object in my app.js file. It did work fine there.

Related

JQuery Custom Validation Rule Mysql function always showing error

I am trying to add a custom validation rule to check if username exists or not. My code:
jQuery.validator.addMethod("checkexist", function(myvalue, element) {
checkifexist(function(result) {
if (result == true)
{
return true;
}
else
{
return false;
}
});
}, 'Does not exists!');
and
async function checkifexist(callback) {
const secret = keytar.getPassword('Userdata', 'MysqlPassword');
secret.then((result) => {
var mysql = require("mysql");
var connection = mysql.createConnection({
host: store.get('ip'),
port: store.get('port'),
user: store.get('username'),
password: result,
database: "database"
});
var querystring = 'SELECT * FROM `testdb`';
try
{
connection.query(querystring, (err, rows, fields) => {
if(err){
return callback("error with query", err);
}
var found;
for (var i in rows)
{
if (some check...)
{
return callback(true);
}
}
return callback(false);
});
connection.end(() => {
});
}
catch { }
});
However, if I check the valditation it correctly outputs true or false on every keypress. I still get only validation errors, though it should be a valid input.

How to keep object state in electron/node.js?

I'm trying to create a Database class using node.js mysql module.
The point is, I want to be able to use the class in different files. But the class itself should keep one connection persistent. So I need somehow to keep object state between files.
My code so far:
main.js
const database = require('./app/database.js');
//// somewhere later in BrowserWindow initianisation
database.init(config);
custom_file.js
const database = require('./app/database.js');
setInterval(
() => {
updateOrdersTable();
}
, 10000
);
function updateOrdersTable() {
console.log('updateOrdersTable');
database.getCurrentOrders((orders) => {
orders.forEach((row) => {
console.log(row);
});
});
}
app/database.js
const mysql = require('mysql');
class Database {
config = {};
connection = {};
customerWindow = {};
stockWindow = {};
init(config) {
this.config = config;
process.stdout.write('Connecting to MySQL Server...');
this.connect();
}
connect() {
this.connection = mysql.createConnection({
host: this.config.database.host,
port: this.config.database.port,
user: this.config.database.user,
password: this.config.database.password,
database: this.config.database.database
});
const that = this;
this.connection.connect(function(err) {
if (err) {
console.log('Database error', err);
setTimeout(that.connect, that.config.database.reconnect_interval * 1000);
return;
}
console.log('Success!');
});
this.connection.on('error', function(err) {
console.log('Database error', err);
setTimeout(that.connect, that.config.database.reconnect_interval * 1000);
});
}
getCurrentOrders(callback) {
this.connection.query("SELECT * FROM current_orders", function (err, result, fields) {
if (err) throw err;
callback(result)
});
}
}
module.exports = new Database();
The error message I'm getting:
Uncaught TypeError: this.connection.query is not a function
at Database.getCurrentOrders (F:\my-app\app\database.js:91)
Line 91 is this:
this.connection.query("SELECT * FROM current_orders", function (err, result, fields) {

Callback Function returns undefined somehow [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
api.js:
var db = require('./db.js');
console.log(searchAccessToken(name,queryDB));
searchAccessToken function:
function searchAccessToken(emailAddress,callback){
var sql = "SELECT accessToken FROM device WHERE email_address = '" + emailAddress + "'";
return callback(sql);
}
queryDB function:
function queryDB(sql){
var token = "";
db(function(err,conn){
conn.query(sql,function(err,results){
if(err){
conn.release();
return err;
}else if(results.length){
token = results[0].accessToken;
}
conn.release();
return token;
});
});
}
db.js
var mysql = require('mysql');
var pool = mysql.createPool({
//development
// host:'localhost',
// user:'root',
// password: '',
// database: 'merchantdev',
// insecureAuth : true
//staging
host:'',
user: '',
password: '',
database: ''
});
var getConnection = function(callback) {
pool.getConnection(function(err, connection) {
if(err) {
return callback(err);
}
callback(null, connection);
});
};
module.exports = getConnection;
I have read the other thread in SOF (How do I return the response from an asynchronous call?) but still unable to find out the mistake in my code. Please do not close this question as I have struggled for hours to find the solution but still couldn't. Console.log returns undefined when it is supposed to return a value.
Your callback function flow is not correct, you are calling asynchronous function that is conn.query
var db = require('./db.js');
// this function not required callback function
// as we are not doing anything asynchronous
function searchAccessToken(emailAddress){
var sql = "SELECT accessToken FROM device WHERE email_address = '" + emailAddress + "'";
return sql;
}
// this function required callback function
// as we are calling 2 asynchronous function
function queryDB(sql, callback){
var token = "";
db(function(err,conn){
conn.query(sql,function(err,results){
if(err){
conn.release();
return callback(err);
}else if(results.length){
token = results[0].accessToken;
}
conn.release();
return callback(null, token);
});
});
}
queryDB(searchAccessToken(name), function callback(err, token) {
if(err) return console.log(err)
console.log(token);
})
Checkout this snippet with callback error handling.
var db = require('./db.js');
function queryDB(sql, callback){
var token = "";
db(function(err,conn){
conn.query(sql,function(err,results){
if(err){
conn.release();
callback(err);
}else if(results && results.length > 0){
token = results[0].accessToken;
}
conn.release();
callback(null, token); //Returning Token as callback response
});
});
}
function searchAccessToken(emailAddress,callback){
var sql = "SELECT accessToken FROM device WHERE email_address = '" + emailAddress + "'";
queryDB(sql, (err, token) => {
if(err) {
callback(err);
} else {
callback(null, token);
}
})
}
searchAccessToken("xyz#gmail.com", (err, token) => {
if(err) {
console.log("Err :", err);
} else {
console.log("Token :", token);
}
});

number variables incrementation - unexpected numbers when running

given the following node\JavaScript code, for some reason the counters variables (failedCounter, successMatchedCounter, successUnmatchedCounter) are counted in an unexpectedly manner when running. I think that it's a matter of scopes and asynchronously but still can't spot the cause.
UPDATE: I think that I should be notified when all calls to connection.query() have finished and only then to log the counters..
See the line of "//BUG: counted numbers are not logged as expected":
var MongoClient = require('mongodb').MongoClient;
var mysql = require('mysql2');
var fs = require('fs');
var dir = './logs';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
var testMode = false;
var mongoUrl = 'mongodb://xxx:27017/yy';
var mySqlconnString = {
host: 'xxxxx',
user: 'xxxx',
password: 'xxxxx',
database: 'xxxxx'
};
var connection = mysql.createConnection(mySqlconnString);
connection.connect(function(err) {
if (err) {
console.log('Error connecting to MySql DB');
return;
}
console.log('Connection established to MySql DB');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) {
console.log('Error connecting to MongoDB');
return;
}
console.log("Connection established to MongoDB");
markSitesAsDeleted(db, function() {
console.log('closing DBs connections..');
connection.end(function(err) {});
db.close();
});
});
});
var failedCounter = 0;
var successMatchedCounter = 0;
var successUnmatchedCounter = 0;
var totalCounter = 0;
var markSitesAsDeleted = function(db, closeConnectionsCallback) {
console.log(`\nMigration process is starting..`);
var cursor = db.collection('someCollection').find({
"isDeleted": true
});
console.log(`Migrating data..\r\n`);
cursor.each(function(err, siteDoc) {
if (siteDoc != null) {
var siteID = Math.trunc(siteDoc._id)
if (testMode === false) {
connection.query(`CALL MarkSiteAsDeleted_3(${siteID})`, function(error, rows) {
if (error) {
//TODO: Print error
failedCounter++;
fs.appendFileSync('logs/log.txt', `Error occured when calling MarkSiteAsDeleted_3 SP for SiteId=${siteID}. see error: ${JSON.stringify(error)}\n`);
} else {
if (rows.affectedRows === 1) { // Has match
successMatchedCounter++;
} else {
successUnmatchedCounter++;
}
}
});
}
totalCounter++;
} else {
//BUG: counted numbers are not logged as expected
fs.appendFileSync('logs/log.txt', `Total: ${totalCounter}, Success and Matched: ${successMatchedCounter}, Success but Unmatched: ${successUnmatchedCounter}, Failed: ${failedCounter}\r\n`);
closeConnectionsCallback();
}
});
};
It sure looks like an async problem. Inside your cursor.each you have async callbacks to handle connection.query. So as the each iterates it makes queries. but all the queries are running asynchronously.
Once the each is finished setting up all the async queries it then hits your else which uses a synchronous write. That is where the problem occurs. Some of your async query handlers have not finished when that write occurs.

Node js custom callback function error

I'm trying to make a simple authentication with node js. Because I read user data from a database, I have to make it asynchronous. Here's my function, which checks if authentication is ok:
function auth(req, callback) {
var header = req.headers['authorization'];
console.log(cb.type);
console.log("Authorization Header is: ", header);
if(!header) {
callback(false);
}
else if(header) {
var tmp = header.split(' ');
var buf = new Buffer(tmp[1], 'base64');
var plain_auth = buf.toString();
console.log("Decoded Authorization ", plain_auth);
var creds = plain_auth.split(':');
var name = creds[0];
var password = creds[1];
User.findOne({name:name, password:password}, function(err, user) {
if (user){
callback(true);
}else {
callback(false);
}
});
}
}
And here I call the function:
auth (req, function (success){
if (!success){
res.setHeader('WWW-Authenticate', 'Basic realm="myRealm');
res.status(401).send("Unauthorized");
}else{
if(user!==req.user) {
res.status(403).send("Unauthorized");
}else{
User.findOneAndUpdate({user:userid}, {user:req.body.user, name:req.body.name, email:req.user.email, password:User.generateHash(req.body.password)},
{upsert:true}, function(err, user) {
if(!err) {
res.status(200).send("OK");
}else{
res.status(400).send("Error");
}
});
}
}
});
This gives me error "TypeError: object is not a function", pointing at "callback(false)". I have no idea what could cause this error, as I pass a function as a parameter, and the first log message prints "[function]". Any help would be appreciated.

Categories

Resources