I'm creating an MVC API with MySQL and node and I got this error while testing with postman.
All the functions are inside class DBConnection();
Initialising Connection
const mysql2 = require("mysql2");
require("dotenv").config();
class DBConnection {
constructor() {
this.db = mysql2.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
});
Checking errors
this.checkConnection();
}
checkConnection() {
this.db.getConnection((err, connection) => {
if (err) {
if (err.code === "PROTOCOL_CONNECTION_LOST") {
console.error("Database connection was closed.");
}
if (err.code === "ER_CON_COUNT_ERROR") {
console.error("Database has too many connections.");
}
if (err.code === "ECONNREFUSED") {
console.error("Database connection was refused.");
}
}
if (connection) {
connection.release();
console.log ("connected to db");
}
return;
});
}
Query
async query(sql, values) {
console.log("++++++++++", this.db);
return new Promise((resolve, reject) => {
const callback = (error, result) => {
if (error) {
console.log(error)
reject(error);
return;
}
resolve(result);
};
// execute will internally call prepare and query
this.db.execute(sql, values, callback);
}).catch((err) => {
const mysqlErrorList = Object.keys(HttpStatusCodes);
// convert mysql errors which in the mysqlErrorList list to http status code
err.status = mysqlErrorList.includes(err.code)
? HttpStatusCodes[err.code]
: err.status;
throw err;
});
}
}
// like ENUM
const HttpStatusCodes = Object.freeze({
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: 422,
ER_DUP_ENTRY: 409,
});
module.exports = new DBConnection().query;
From the response, I got error code 500 Internal Server Error. I'm assuming the error is resulting from the constructor, but any suggestions are welcomed.
question from:
https://stackoverflow.com/questions/65949045/error-message-db-is-not-defined-node 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…