Home > Mobile >  How to pass mysql2/promise connection object cross-file
How to pass mysql2/promise connection object cross-file

Time:05-16

I am currently trying to make a mysql based login system to a much bigger project of mine. While log in-ing and log out-ing, I am also required to calculate xp. To do this, I'm running a function from an another file from my index.js, but node.js returns an error saying that conn.query is not a function. Conn.query works inside my index.js, so probably the object isn't correctly passed into the function. I have tried to solve this problem with a class, but that failed in basically the same way. This is how my files look like:

index.js:

const mysql2 = require('mysql2/promise');
const express = require("express");
const xp = require("./xp.js");
const app = express();
var colors = require('colors'); // console coloring


console.log("Checking database connection...".yellow); // .yellow just colors the text
try {
    conn = mysql2.createConnection({
        database: "databasename",
        host: "localhost",
        user: "root",
        password: "",
    });
} catch (err) {
    console.log(
        `${"Test failed, the following error has occured:".red} ${
            `${err.toString().split("Error: ")[1]}`.yellow
        }`
    );
}
console.log("Test successful! The database connection is valid!".green);
// ...

app.listen(port, async () => {
    xp.CalculateXp(conn, "fe417913-b0b5-4c72-9f39-0e986b830c08", "serial");
}

xp.js:

const mysql2 = require('mysql2/promise');
async function CalculateXp(conn, serial, entryLeaveID) {
    const [entryList, _fields] = await conn.query(`SELECT EntryTime,LeaveTime,EntryDate,LeaveDate,ID FROM entryleavingdata WHERE USRSERIALPRIVATE=? AND HasBeenCalculated=? AND ID=? AND organiserConfirmation=? LIMIT 1`, [serial, 0, entryLeaveID, 1]);
    const entry = entryList[0]
    // every query gives the same output
    // ....
}
module.exports = { CalculateXp };

I am getting the following error:

TypeError: conn.query is not a function
    at Object.CalculateXp (/home/name/Desktop/new/xp.js:46:45)
    at Server.<anonymous> (/home/name/Desktop/new/index.js:88:8)
    at Object.onceWrapper (node:events:641:28)
    at Server.emit (node:events:527:28)
    at emitListeningNT (node:net:1414:10)
    at processTicksAndRejections (node:internal/process/task_queues:82:21)

I am using node v17.9.0 on Ubuntu. Is there any way to provide the correct connection object to my function while keeping the two files separated? Do I just need to merge the files?

Thanks in advance.

CodePudding user response:

You should declare conn somewhere before try - let conn.

Now it's undefined when you try to use it.

CodePudding user response:

createConnection returns a promise that resolves to a connection. You're correctly passing it to the other file, but promises have functions like .then() and .catch(). You should probably await it before sending the result to the other function.

  • Related