0

I have simple 2 js files one is the entry point (main.js) and the other is the connection and methods. Here's the class

const mysql = require("mysql2/promise");

  class MySQLBackend {
    constructor() {
      this.connection = null;
    }

  async connect() {
    this.connection = await mysql.createConnection({
      host: "localhost",
      port: 3308,
      user: "root",
      password: "",
      database: "dbname",
    });
    return this.connection;
  }

  async disconnect() {
    this.connection.end();
  }

  async insert() {
    return this.connection.query(
      "insert into coins (value_date, coin_value) values ('2021-03-20 10:12:13', '4.25')"
    );
  }


  async test() {
    const connection = this.connect();
    if (connection) {
      console.log("connected!!"); //prints connected!!
      await this.insert();
    } else {
      throw new Error("Error connecting to mysql");
    }
  }
}

module.exports = MySQLBackend;

In main.js which is the entry point

const MySQLBackend = require("./services/backend/MySQLBackend");

async function runMySQL() {
  const mysqlBackend = new MySQLBackend();
  return mysqlBackend.test();
}

runMySQL()
  .then((result) => {
    console.log(result);
  })
  .catch((err) => console.error(err));

But I get

connected!!
TypeError: Cannot read property 'query' of null

I'm learning Node and don't know why I get this issue and how to solve it

2 Answers 2

1

That's how I go t it to work

async insert() {
 return this.connection.query(
  "insert into table (field) values ('value')"
 );
}

async test() {
  *this.connection* = *await* this.connect();
  if (this.connection) {
    console.log("connected!!");
    await this.insert();
  } else {
  throw new Error("Error connecting to mysql");
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to bind the context of this for the test method within your MySQLBackend class constructor

So your constructor should look like this

constructor() {
   this.connection = null;
   this.test = this.test.bind(this)
}

7 Comments

Oops! That's weird. You can try to bind the insert method too or redefine the methods with arrow functions so they look like this async test = () => { instead of this async test() {
I think the problem is in mysql2 I tried mysql and it worked fine don't know why
got the same error with mysql with the same file structure (oop with constructor)
Yeah, that makes sense. Because you're calling runMySQL() in a context different from where MySQLBackend is defined you run into that error
I didn't assign this.connection to this.connect() and added await too so it's this.connection = await this.connect();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.