Binato/server/objects/Database.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-11-16 15:25:46 +00:00
import { ConsoleHelper } from "../../ConsoleHelper";
import { createPool, Pool } from "mysql2";
export class Database {
private connectionPool:Pool;
private static readonly CONNECTION_LIMIT = 128;
2022-11-17 00:29:07 +00:00
public connected:boolean = false;
2023-08-20 13:03:01 +01:00
public constructor(databaseAddress:string, databasePort:number = 3306, databaseUsername:string, databasePassword:string, databaseName:string) {
2022-11-16 15:25:46 +00:00
this.connectionPool = createPool({
connectionLimit: Database.CONNECTION_LIMIT,
host: databaseAddress,
port: databasePort,
user: databaseUsername,
password: databasePassword,
database: databaseName
});
2023-08-20 13:03:01 +01:00
ConsoleHelper.printInfo(`Connected DB connection pool. MAX_CONNECTIONS = ${Database.CONNECTION_LIMIT}`);
2022-11-16 15:25:46 +00:00
}
public query(query = "", data?:Array<any>) {
const limited = query.includes("LIMIT 1");
2022-11-17 00:29:07 +00:00
return new Promise<any>((resolve, reject) => {
2022-11-16 15:25:46 +00:00
this.connectionPool.getConnection((err, connection) => {
if (err) {
reject(err);
try {
connection.release();
} catch (e) {
ConsoleHelper.printError("Failed to release mysql connection\n" + err);
}
} else {
// Use old query
if (data == null) {
connection.query(query, (err, data) => {
if (err) {
reject(err);
connection.release();
} else {
dataReceived(resolve, data, limited);
connection.release();
}
});
}
// Use new prepared statements w/ placeholders
else {
connection.execute(query, data, (err, data) => {
if (err) {
reject(err);
connection.release();
} else {
dataReceived(resolve, data, limited);
connection.release();
}
});
}
}
});
});
}
}
function dataReceived(resolveCallback:(value:unknown) => void, data:any, limited:boolean = false) : void {
if (limited) resolveCallback(data[0]);
else resolveCallback(data);
}