import fs from "fs"; import path from "path"; import grabDSQLConnection from "../../utils/grab-dsql-connection"; import { DSQL_TableSchemaType } from "../../types"; import { Connection, ConnectionConfig } from "mariadb"; type Param = { query: string; values?: string[] | object; noErrorLogs?: boolean; database?: string; tableSchema?: DSQL_TableSchemaType; config?: ConnectionConfig; }; /** * # Main DB Handler Function * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database */ export default async function dbHandler< T extends { [k: string]: any } = { [k: string]: any } >({ query, values, noErrorLogs, database, config, }: Param): Promise { let CONNECTION: Connection | undefined; let results: T[] | T | null; try { CONNECTION = await grabDSQLConnection({ database, config }); if (query && values) { const queryResults = await CONNECTION.query(query, values); results = queryResults[0]; } else { const queryResults = await CONNECTION.query(query); results = queryResults[0]; } } catch (error: any) { console.log("Connection Info =>", CONNECTION?.info); if ( error.message && typeof error.message == "string" && error.message.match(/Access denied for user.*password/i) ) { throw new Error("Authentication Failed!"); } if (!noErrorLogs) { console.log("ERROR in dbHandler =>", error.message); console.log(error); const tmpFolder = path.resolve(process.cwd(), "./.tmp"); if (!fs.existsSync(tmpFolder)) fs.mkdirSync(tmpFolder, { recursive: true }); fs.appendFileSync( path.resolve(tmpFolder, "./dbErrorLogs.txt"), JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8" ); } results = null; } finally { await CONNECTION?.end(); } if (results) { return results; } else { return null; } }