I'm trying to return a value from a class but it's coming up undefined.
index.js
import DB from "./db.js"
import express from "express";
import cors from "cors";
const database = new DB();
app.get("/", (req, res) => {
const data = database.selectAllFromProducts();
console.log(data); // Returns undefined
});
app.listen(process.env.PORT, () =>
console.log(`Listening on Port ${process.env.PORT}`)
);
db.js
class DB {
constructor() {
this.connection = this.initialize();
}
initialize() {
return mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
selectAllFromProducts() {
this.initialize();
this.connection.query(`select * from ${process.env.DB_PRODUCTS_TABLE};`,
(err, results, fields) => {return results});
}
}
I have a front end that is sending the GET request and that is successful so it's not a routing problem. Console.logging the results works from db.js so I know it's not a MYSQL problem but for whatever reason it comes up blank in index.js. Thanks in advance for any help!
EDIT - I have module.exports = DB I just forgot to include it because I only included partial bits of the file. Importing works just fine for me because I'm using babel and type: module in my package.json. I couldn't tag node because it requires 1500 rep.