Trying to developing REST API in Node.Js by using MySQL Database. Could you please help me to write some better code?
Two most important questions here,
1 - How we can take the createConnection logic out of userModel.js?
2 - Shall I end the connection on every API call?
Predicted Answer
filename : db.js
const mysql = require('mysql2/promise');
module.exports = async function(){
return await mysql.createConnection({host:'localhost', user: 'user', password:'pass', database: 'database'});
}
and in userModel.js
const mysql = require('db.js');
module.exports.getProfile(user_id){
try{
const [rows, fields] = await db.execute('SELECT * FROM `table` WHERE `user_id` = ?', [1]);
console.log(rows);
}catch(err){
console.log(err);
}
await db.end();
}
Above code implementation will generate errors If we try to hit API again with "{ Error: Can't add new command when connection is in closed state at PromiseConnection.execute"
Perhaps If is use this below-given approach which seems silly we can call same API again n again without any error.
Also there are many functions in userModel.js and in this case, we must create and end connection with every API method.
userModel.js
const mysql = require('mysql2/promise');
const db = await mysql.createConnection({host:'localhost', user: 'user', password:'pass', database: 'database'});
try{
const [rows, fields] = await db.execute('SELECT * FROM `table` WHERE `user_id` = ?', [1]);
console.log(rows);
}catch(err){
console.log(err);
}
await db.end();
Any advice will be helpful. Regards,