Validating data from mysql query in express.js - mysql

I have a post api which i want to validate data before inserting it into data base .
I want to check if the customerCode from the body exists in database or not .
this is my code but it always returns " Cannot read properties of undefined (reading '0')"
app.post('/CreateCustomer', (req, res) => {
pool.getConnection((err, connection) => {
if (err) throw err
const params = req.body
connection.query('SELECT CustomerCode FROM Customers WHERE CustomerCode = ?', params.CustomerCode, (err, rows) => {
// connection.release() // return the connection to pool
if (rows[0] == undefined) {
connection.query('INSERT INTO Customers SET ?', params, (err, rows) => {
connection.release() // return the connection to pool
if (!err) {
res.send(`Customers with the record ID has been added.`)
} else {
console.log(err)
}
console.log('The data from beer table are:11 \n', rows)
})
} else {
res.send("Csutomer Code Already taken!")
}
})
})
})

Related

Node Api rest - change database dynamically|

Is it possible to change the pool config database?
I have a rest API with node/express, and I have multiple databases.
So I need that when a user.company login in my frontend, the API rest, choose the database that user should use.
My configuration file for the bank is this .env
JWT_KEY=XXXXXXX
POOL1_USER=root
POOL1_PASSWORD=xxxxxx
POOL1_DATABASE=data1
POOL1_HOST=host.domain.com
POOL1_PORT=3306
Meu arquivo db.js é este:
const mysql = require("mysql");
const pool1 = mysql.createPool({
connectionLimit: 10,
user: process.env.POOL1_USER,
password: process.env.POOL1_PASSWORD,
database: process.env.POOL1_DATABASE,
host: process.env.POOL1_HOST,
port: process.env.POOL1_PORT,
});
module.exports = { pool1 };
Is this my controllers.js file?
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};
I need to dynamically change the database, as I have the same frontend for the same rest API, but I have multiple databases that can even be on different hosts.
It may be that what I'm trying to implement is not possible, so does anyone have any different suggestions?
Before you use the query to select a table from a database, you need to switch the database, use this query to achieve that.
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
then after it use the query that you want like this
const mysql = require("../db").pool1;
exports.adminGroup = (req, res, next) => {
mysql.getConnection((error, conn) => {
if (error) {
return res.status(500).send({ error: error });
}
con.query("USE your_db_name", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
conn.query(
"INSERT INTO adminGroup SET ?",
[req.body],
(error, results) => {
conn.release();
if (error) {
return res.status(500).send({ error: error });
}
response = {
mensagem: "Group add",
grupoCriado: {
id: results.insertId,
grupo: req.body.group,
},
};
return res.status(201).send(response);
}
);
});
};

Send back rows and readstream in nodejs

Hey I would like to send back an image downloaded from s3 and data from MySQL database but i'm not sure if its even possible and if it is, how to do it.
Any help is welcome thanks!
app.get('/api/users/:id', (req, res) => {
var id = req.params.id;
pool.getConnection((err, connection) => {
if (err) throw err
console.log('connected as id ' + connection.threadId)
connection.query(`SELECT username, picture, DATE_FORMAT(creation_date, "%d %M %Y") as creation_date from users where idusers = ${id}`, (err, rows) => {
connection.release() // return the connection to pool
if (!err) {
const readStream = getFileStream(rows[0].picture);
readStream.pipe(res);
res.send(rows[0])
} else {
console.log(err)
}
})
});
})

Calling mysql queries dependent on another query in node

can anyone help me.
I need to get result of queryA [which is an update query that returns ROW_COUNT( )], see if the result is equal to 1.
If not, just return it via res.json
If yes, call queryB [which returns a set of rows].
After which, I have to loop and call queryC to update each row. It has to be one at a time because the queryC is also inserting auditTrails within the stored procedure.
This is the source code:
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*GET rows to be updated*/
const GetRows = connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE rows*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
});
});
});
}
res.json(updateCus);
connection.end();
});
Error:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Query'
then another one at the bottom:
throw er; //Unhandled 'error' event
You are missing 'await' before the mysql.createConnection(config) and connection.query call, since these are asynchronous functions. Also in your code connection.end() should be inside the callback.
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = await mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = await connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
connection.end();
if (error) {
return console.error(error.message);
}
});
});
});
}else{
connection.end();
return res.status(200).json({
customer:updateCus});
}
});

MySQL Node JS DELETE no working - 0 rows affected

I am trying to create a post route that will delete a user's data from several tables. I checked in mySQL workbench that the database user has this privilege. However when I click delete on the frontend, the queries appear to run but the rows do not get deleted. Can you someone please tell me where I am going wrong?
app.post('/disposal', redirectLogin, async(req, res) => {
const user = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
await connection.query(userStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(holdingsStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(cashStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
connection.query(tradesStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
});
});
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})
I needed to change user = res.locals to { user } = res.locals as it the former was coming back 'undefined' as it was not properly extracting.
You don't need to nest the calls if you are using async/await.
As the res.locals is an object which contains the user property, you have to get the user property.
You could get it by using Object destructuring syntax.
Try this.
app.post('/disposal', redirectLogin, async (req, res) => {
const { user } = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
try {
let results = await connection.query(userStmt);
console.log(results);
let holdinResult = await connection.query(holdingsStmt);
console.log(holdinResult);
let cashResult = await connection.query(cashStmt);
console.log(cashResult);
let tradesResult = await connection.query(tradesStmt);
console.log(tradesResult);
} catch (error) {
throw error
}
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})

Node.js - Express & mysql TypeError: res.json is not a function although insert is successful

Although I have a successful insert I get an error (TypeError: res.json is not a function) when I want to return a json message upon. This is my setup:
const express = require('express');
module.exports = {
signup: async (req, res, next) => {
const { email, username, password } = req.value.body;
const connection = require('../config/dbconnection');
connection.query("SELECT * FROM tbl_users WHERE email = ?",[email], function(err, rows) {
if (rows.length) {
return res.json({ err: 'Email already exist'});
} else {
var newUserMysql = {
email: email,
username: username,
password: password
};
var insertQuery = "INSERT INTO tbl_users ( email, username, password ) values (?,?,?)";
connection.query(insertQuery,[newUserMysql.email, newUserMysql.username, newUserMysql.password],function(err, res, rows) {
if(err){
console.log('Insert error');
//res.json({ err: 'Insert error'});
} else {
console.log('Insert successful');
return res.json({ 'success': 'Insert successful'});
//return done(null, newUserMysql);
}
});
}
});
}
How can I return a json on successfull insert?
Your function's res parameter is hidden by the res return value from the connection.query call.
Rename the res parameter of this call to result (for example) and you should be fine:
connection.query(insertQuery,[newUserMysql.email, newUserMysql.username, newUserMysql.password],function(err, result, rows) {
if(err){
console.log('Insert error');
//res.json({ err: 'Insert error'});
} else {
console.log('Insert successful');
return res.json({ 'success': 'Insert successful'});
//return done(null, newUserMysql);
}
});
When you have nested scopes with conflicting variable names, the variable the closest (scope-wise) from where you reference this conflicting name will be used.
You're redefining res in your connection.query(insertQuery, [.....], function(err, res, rows) { ...}) function.
That res overrules the res from your express router within the scope of that function