50 lines
1.1 KiB
TypeScript
50 lines
1.1 KiB
TypeScript
import { Plugin } from "../plugin.class";
|
|
import * as mysql from "mysql2/promise";
|
|
|
|
export class DatabasePlugin extends Plugin {
|
|
constructor(name: string, private dbConnection: any) {
|
|
if (!dbConnection || typeof dbConnection.execute !== "function") {
|
|
throw new Error(
|
|
"Invalid database connection: must be a mysql2 connection with execute method"
|
|
);
|
|
}
|
|
|
|
super(name, ["execute"]);
|
|
}
|
|
|
|
static async init(
|
|
name: string,
|
|
config: {
|
|
host: string;
|
|
port: number;
|
|
user: string;
|
|
password: string;
|
|
database: string;
|
|
}
|
|
): Promise<DatabasePlugin> {
|
|
const dbConnection = await mysql.createConnection({
|
|
host: config.host,
|
|
user: config.user,
|
|
port: config.port,
|
|
password: config.password,
|
|
database: config.database,
|
|
enableKeepAlive: true,
|
|
});
|
|
|
|
return new DatabasePlugin(name, dbConnection);
|
|
}
|
|
|
|
async execute(query): Promise<any> {
|
|
const [rows, fields] = await this.dbConnection.query(query);
|
|
|
|
return {
|
|
rows: rows,
|
|
fields: fields ?? [],
|
|
};
|
|
}
|
|
|
|
onFinish() {
|
|
this.dbConnection.end();
|
|
}
|
|
}
|