简体   繁体   中英

async await mysql2/promise and ending connection

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,

  1. Connection can be done when your server starts. You should put this code in the file where you are starting the server.

  2. Creating connections can be expensive and can affect your app performance. You should use connection pools

On a slight different note, It's not a good idea to hard code the parameters to connect to the database. You should keep a config file from which these values can be read based on an environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM