I want to use the MYSQL2 promise API, and am struggling with the proper way to connect to the database.
Hoping for someone to weigh in on the correct way.
Edit for clarity: The issue is that mysql.createConnection() returns a promise, so when setting it equal to my connection variable so I can then make queries on it in the future, it is equal to the promise, and not the result of the promise. Thus the need for AWAIT or .then chain.
Option 1: Top level await by making the whole project a module.
import dotenv from 'dotenv'
dotenv.config()
import mysql from 'mysql2/promise.js'
import express from 'express'
import ejs from 'ejs'
import {faker} from '@faker-js/faker'
import path from 'path'
const app = express();
app.set("view engine", "ejs");
app.use(express.json())
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: process.env.SQL_PASSWORD,
database: "joinus"
})
connection.connect()
app.get('/users', async(req,res,next) => {
const query = await connection.query('SELECT * FROM users')
res.send(query)
})
app.listen(5000, () => {
console.log("I hear you");
});
Option 2: Wrap the entire app in an async function main, and call that function to start execution of the app. This way I can await without converting to a module and using top level await.
if (process.env.NODE_env !== "production") {
require("dotenv").config();
}
const mysql = require("mysql2/promise");
const express = require("express");
const ejs = require("ejs");
const { faker } = require('@faker-js/faker');
const path = require("path");
const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname + "/views"));
app.use(express.json())
async function main() {
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: process.env.SQL_PASSWORD,
database: "joinus"
})
app.get('/users', async(req,res,next) => {
const query = await connection.query('SELECT * FROM users')
res.send(query)
})
app.listen(5000, () => {
console.log("I hear you");
});
}
main()
Option 3: Chain a then onto my connection creation and proceed as normal
if (process.env.NODE_env !== "production") {
require("dotenv").config();
}
const mysql = require("mysql2/promise");
const express = require("express");
const ejs = require("ejs");
const { faker } = require("@faker-js/faker");
const path = require("path");
const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname + "/views"));
app.use(express.json());
let connection;
mysql
.createConnection({
host: "localhost",
user: "root",
password: process.env.SQL_PASSWORD,
database: "joinus"
}).then((result) => connection = result)
app.get("/users", async (req, res, next) => {
const query = await connection.query("SELECT * FROM users");
res.send(query);
});
app.listen(5000, () => {
console.log("I hear you");
});
Option 4: ???
Please guide a hobbyist/new coder towards the right path.