简体   繁体   中英

The correct way to passing connection as parameter to different function in mysql2 nodejs

it's my sample code

// database.js
exports.connection = mysql2.createPool({
      host: process.env.DB_HOST,
      user: process.env.DB_USERNAME,
      password: process.env.DB_PASS,
      database: process.env.DB_NAME,
      supportBigNumbers: true,
      bigNumberStrings: true,
      dateStrings: true,
    });
// users.js
const { connection } = require('./database.js');

async function createUsers(params) {
  const conn = await connection.getConnection();
  try {
    await conn.beginTransaction();
    const sql = "INSERT INTO users (name,pass) VALUES (?,?)";
    const [id] = await conn.query(sql, [params.user, params.pass]);

    // i want to passing connection to any function like this
    await loginRoles(conn, { id: id.insertId, role: "user" });

    await conn.commit();
    return id.insertId;
  } catch (error) {
    await conn.rollback();
    return Promise.reject(error);
  } finally {
    conn.release();
  }
}
async function loginRoles(conn, params) {
  try {
    const sql = "INSERT INTO login (id, role) VALUES (?,?)";
    return conn.query(sql, [params.id, params.role]);
  } catch (error) {
    return Promise.reject(error);
  }
}

Is it the right way to passing connection as parameter to different function? I've tested this code, and it is works.. But is this the right way?

connection is just an object that stores some methods to interact with a database, so it's ok to pass this object to some functions. One thing you should remember: try to not modify this object in functions you invoke. It can lead to memory leaks.

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