Passing parameters to the constructor of a Singleton - javascript

var Database = (function(host, username, password, database) {
var connection = mysql.createConnection({
host: host,
user: username,
password: password,
database: database
});
return {
//all my functions
};
}());
I am trying to make a Database singleton in node to communicate with my database.
But how to I pass the arguments, (host, username, password, database) into it when I call it?
I cant do:
var db = new Database(HOST, USERNAME, PASSWORD, DATABASE);
since database is a singleton...
Also, how do I make a constructor inside Database, and how do I pass arguments into it??

The () on the final line is the list of arguments being passed to the function, and it is currently empty. Simply put your arguments there:
var Database = (function(host, username, password, database) {
var connection = mysql.createConnection({
host: host,
user: username,
password: password,
database: database
});
return {
//all my functions
};
}(HOST, USERNAME, PASSWORD, DATABASE));

Related

hashed password not works with me

I don't know why this hash password code does not work.
I did install bcrypt, also, it should go to the line (res.send("testing"))if the passwords are the same but anyway in all situations password does not match is coming even they are the same.
Here is my code:
const mysql = require('mysql');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db = mysql.createConnection({
host: process.env.DATABASE_host,
user: process.env.DATABASE_user,
password: process.env.DATABASE_password,
database: process.env.DATABASE,
});
exports.form = (req, res) => {
console.log(req.body);
const { name, email, password, confirmPassword } = req.body;
db.query(
'SELECT email FROM users WHERE email=?',
[email],
async (error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
return res.render('form', {
message: 'that email is already in use',
});
} else if (password !== confirmPassword) {
return res.render('form', {
message: 'passwords not match',
});
}
let hashedPassword = await bcrypt.hash('password', 8);
console.log(hashedPassword);
res.send('testing');
}
);
};
``
[enter image description here][1]
[1]: https://i.stack.imgur.com/ToNvN.png
and always (passwords not match) comes even as u see in pic the passwords are same
Every time you call bcrypt.hash() you will get a different hash string, even with the same password, this is because the hashes are salted.
To check whether the hashes are equal, you need to test with bcrypt.compare(), you cannot compare to hashes directly. Some libraries also call it bcrypt.verify().
Edit: Assuming you use the node.bcrypt.js library:
const bcrypt = require('bcrypt');
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
let hashToStoreInDb = bcrypt.hashSync('mypassword', 10);
// Check if the entered login password matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
let existingHashFromDb = hashToStoreInDb;
const isPasswordCorrect = bcrypt.compareSync('mypassword', existingHashFromDb);

Mongoose: How do I pass data from a document created afterwards into a document created right before?

In my signup request, I use create two documents (in separate collections) based on two different schemas: a User model and a Client model. For context, a client will be one object referencing an array of many Users.
The User scheme includes 'clientID' field, which should hold the User's Client's ._id. Likewise, the Client's 'users' field would include an array of Users attached. The latter works OK.
On signup, I create a User, and then a Client. I am able to pass the User._id into the Client's array of users no problem. But, how do I get the Client's ._id into the User's clientID field?
The code below errors saying: Cannot access 'client' before initialization - I understand why this is happening because of the order of code.
But how do I get my code to reciprocate so that I can add the Client._id to the User's clientID field? I am sure this is a common problem, but I can't find the relevant doc on Mongoose's docs.
If anyone could help? Many thanks!
module.exports.signup = async (req, res) => {
// extract data from the req.body
const { email, password, fName, lName, companyName, teams } = req.body;
try {
// create a new user on the User model
const user = await User.create({
email: email,
password: password,
clientID: client._id,
});
// create a new client on the Client model
const client = await Client.create({
companyName: companyName,
users: user._id,
});
res.status(201).json(user);
} catch (err) {
const errors = handleErrors(err);
res.status(400).json(errors);
}
};
You can instead use a specific objectId for the client when you create it and reference it later.
Just copy past the whole code:
const {ObjectID} = require('mongodb');
module.exports.signup = async (req, res) => {
// extract data from the req.body
const { email, password, fName, lName, companyName, teams } = req.body;
try {
const clientId = ObjectID();
// create a new user on the User model
const user = await User.create({
email: email,
password: password,
clientID: clientId,
});
// create a new client on the Client model
const client = await Client.create({
companyName: companyName,
users: user._id,
_id: clientId
});
res.status(201).json(user);
} catch (err) {
const errors = handleErrors(err);
res.status(400).json(errors);
}
};
Another solution is that you can create a user without clientId and after you create client you can update the user with the created client.id:
const user = await User.create({
email: email,
password: password,
// clientID: clientId,
});
// create a new client on the Client model
const client = await Client.create({
companyName: companyName,
users: user._id,
});
user.clientId = client._id;
await user.save();

What is the correct way to be using the Node.js MySQL Library?

Currently I am playing around with the MySQL library in Node.js however I have a question about the correct/most efficient way to be using this library.
According to w3schools the correct way to make a single query is to use code like this
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
However, say I wanted to make multiple queries which would be executed by an event for example how would I handle this? Should I create an "initialise" function which is executed as soon as the program runs such as this?
var mysql = require('mysql');
var database;
//Initialise database
function setupDatabase() {
database = mysql.createConnection({
host: token.host,
user: token.user,
password: token.password,
database: token.database,
port: token.port
});
}
//Imagine this could be called at any time after execution
function event() {
if(database != null) {
database.connect(function(err) {
if (err) throw err;
database.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
}
}
And also do I have to connect to the database each time I make a query or can I add the "database.connect" call to my setupDatabase function such as this?
var mysql = require('mysql');
var database;
//Initialise database
function setupDatabase() {
database = mysql.createConnection({
host: token.host,
user: token.user,
password: token.password,
database: token.database,
port: token.port
});
if(database != null) {
database.connect(function(err) {
if (err) throw err;
});
}
}
//Imagine this could be called at any time after execution
function event() {
if(database != null) {
database.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
}
}
My main concern is that calling the con.connect function every single time I make a query would be slow and although these are asynchronous I want to be using the correct/most efficient way possible. Feel free to correct me on any mistakes with the last two code snippets I have only tested the first one so far.
You have to make database connection only once per application livetime (unless you have disconnects). Then you may have as much queries as you want.
Just put database connection routine somewhere in sepparate file and then require it in your applicatin initialisation step.
// mysql.js
const mysql = require('mysql');
module.exports = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
Or require it anywhere you need database connection - it will return connected database object without reruning that code again and again.
// inex.js
const databse = require('./mysql')
database.query("SELECT * FROM customers")
I created a file which include a function that holds a pool and handles the connection to the database like this
let _this = {};
let POOL = null;
function getPool() {
return new Promise((resolve, reject) => {
if(POOL != null) {
resolve(POOL);
} else {
//create connection pool
POOL = connectionPool;
resolve(POOL);
}
});
}
function closePool(){
// close pool here
}
_this.getPool = getPool;
_this.closePool = closePool;
module.exports = _this;
Now you can call getPool() and will recive a pool of connections where you can execute your queries with.

Where to put MySQL connection to avoid code repetition in Node.js

I'm using the mysql module in Node.js. In my model file, currently, I'm specifying the connection constants in each method. However, this is taking up a lot of space and I know it's not ideal.
Here's what that looks like.
doSomething: () => {
var connection = mysql.createConnection({
host : config.database.host,
database : config.database.database,
user : config.database.user,
password : config.database.password
});
connection.query( ... );
connection.destroy();
},
doSomethingElse: () => {
var connection = mysql.createConnection({
host : config.database.host,
database : config.database.database,
user : config.database.user,
password : config.database.password
});
connection.query( ... );
connection.destroy();
},
Could anyone recommend a way to tidy things up a bit and reduce the redundant code here?
Create the connection once and pass it to module exports.
const mysql = require("mysql");
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "db"
});
module.exports = conn;
Then you can import it in other files and use it.
var dbConnection = require('./dbConnection');
dbConnection.query();
However, instead of using createConnection, I recommend using createPool instead.
Connections can be pooled to ease sharing a single connection, or
managing multiple connections.
const mysql = require("mysql");
const conn = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "db"
});
module.exports = conn;
You can use it like this. Make sure to release the connection after fetching data from the table:
var connectionPool = require('./dbConnection');
connectionPool.getConnection((err, connection) => {
connection.query('SELECT * FROM table', (error, result) {
connection.release();
if(error) throw error;
});
});
To close all connections in the pool:
connectionPool.end(function (err) {
// all connections in the pool have ended
});

node js Insert into mysql variable not work

I am using MySql with node.js
i have this query and it works:
connection.query('insert into username (name) values ("msg")', function(err, rows, fields) {
if(!err) {
} });
it inserts the string "msg", not the value of the variable msg, but when I want to insert the variable this does not work:
connection.query('insert into username (name) values '+ msg, function(err, rows, fields) {
if(!err) {
} });
for example:
var msg = "hello world!";
You are missing the parenthesis and the quotes that make a valid insert statement in the second case. You are building a sql statement that looks like this:
'insert into username (name) values hello world'
which is malformed. Use the util module to make your string formatting easier:
var util - require('util');
var mySql = util.format('insert into username (name) values ("%s")', 'hello world');
connection.query(mySql, function(err, rows, fields) {
if(!err) {
} });
try this code
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'db_name'
});
connection.query(`INSERT INTO user_table (name, mail, pass) VALUES ('${user_name}', '${user_name}', '${user_name}');`, function (err, result, fields) {
if (err) throw err;
});

Categories