Hi. I am looking to create a reusable query with MySQL and NodeJS
The first step I took after the DB connection was to create a data access object and interact with the DB while using promises. To stay relative secure, I am using placeholders:
I want to create functions to be reused. So if I am creating one function for insert, I need to use same function to insert records in different tables while using parameters.
The Data access layer looks like this: Here I am using parameters that will go to each function and replace the placeholders from the sql statements.
/*
Insert user accepts three parameters. Statement from mysql, table marked with ?? in the statement and the
payload object that have to match the database columns
*/
insertRecord: (sqlStatement, table, payload) => {
return new Promise((resolve, reject) => {
db.query(sqlStatement, [table, payload], (error, response) => {
if (error) return reject(error);
return resolve(response);
});
});
},
/*
This function accepts four parametters. The first parameter is the statement. Second parameter is the table selector
marked with ?? in the statement.
The selector is the row, and the value specified
*/
selectSimpleStatement: (sqlStatement, table, row, value) => {
return new Promise((resolve, reject) => {
db.query(sqlStatement, [table, row, value], (error, response) => {
if (error) return reject(error);
else return resolve(response);
});
});
}
}
The second implementation was to create all the MySQL queries separately because I wanted to keep it Clean
module.exports = { insertStatement: 'INSERT INTO ?? SET ?', sqlSimpleSelect: 'SELECT * FROM ?? WHERE ? = ?' }
Using the first sql statement was easy. I worked to insert in all the tables with the same function. But the select is a pain. With postman I am getting empty arrays even if the values are correct...
const { sqlSimpleSelect } = require('../../database/statements.js');
const bcrypt = require('bcrypt');
exports.add = async (req, res, next) => {
const {username, password} = req.body;
try {
// Select from users where username = username variable
const user = await selectSimpleStatement(sqlSimpleSelect, 'users', 'username', username);
res.send(user);
}
catch (error) {
res.send(error)
}
}```
I am getting empty array. Can please help me?
Thanks, Daniel