如何在单独的文件中正确创建带有错误处理的 mysql2 连接

问题描述

我尝试使用 node.js 和 mysql2 实现以下连接方法,但缺少某些内容,并且出现各种错误(主要是 db.query is not a function)。

密钥如下:

  • 重用已经创建的连接
  • 错误处理
  • 如果连接失败自动重新连接

原始(检查下面的更新):

//dbConnection.js

const MysqL = require('MysqL2/promise');
const dbConfig = {
    host: 'localhost',user: 'user',database: 'db',password: 'pass'
};

var connection;

//Exporting to use it elsewhere
module.exports = async function connect() { 
    if (connection){
        //so if the connection is already exists use it again
        return connection;
    }
    try {
        connection = await MysqL.createConnection(dbConfig);    
        console.info("Connected to MysqL on '" + db_config.host + "'");
        return connection;
    } catch (error) {
        console.error('Error when connecting to MysqL:',error);
        // auto retry in 5 seconds
        setTimeout(connect,5000);
    }
}
//dbroutes.js

const db = require('./dbConnection.js');

dbrouter.get('/get_user',async (req,res,/* next */) => {
    const userId = req.userId;
    await db.query(
        `SELECT * FROM users WHERE id = ${userId};`,(err,result) => {
            return res.status(200).send({
                msg: 'success',user: result
            });
        }
    );
});

更新:

我能够使它工作,但我不确定这是最好的方法,所以我要求您提出任何改进意见。

//dbConnection.js

const MysqL = require('MysqL2/promise');

const db_config = {
    host: 'localhost',user: 'root',database: 'bln',password: ''
};

var connection;
const connect = async function () { 
    if (connection){
        return connection;
    }

    try {
        connection = await MysqL.createConnection(db_config);
        console.info("Connected to MysqL on '" + db_config.host + "'");
        return connection;
    } catch (error) {
        console.error('Error when connecting to db:',error);
        connection = undefined;
        setTimeout(connect,5000);
    }
}

module.exports = connect;

//dbroutes.js

const dbc = require('./dbConnection.js');

dbrouter.post('/login',userMiddleware.validateLogin,res) => {
    const db = await dbc();
    const [results] = await db.execute(`SELECT * FROM users WHERE email = ?;`,[req.body.email]);
  return res.status(401).send({
        msg: 'success',user: result
    });
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)