This commit is contained in:
Benjamin Toby
2025-07-06 15:32:28 +01:00
parent 3597b11342
commit b38ddc9f21
50 changed files with 453 additions and 245 deletions
+22 -12
View File
@@ -1,6 +1,6 @@
import { ServerlessMysql } from "serverless-mysql";
import debugLog from "../logging/debug-log";
import { DSQLErrorObject } from "../../types";
import type { ConnectionConfig, Pool } from "mariadb";
export type ConnDBHandlerQueryObject = {
query: string;
@@ -9,8 +9,9 @@ export type ConnDBHandlerQueryObject = {
type Return<ReturnType = any> =
| ReturnType
| ReturnType[]
| null
| { error?: string; errors?: DSQLErrorObject[] };
| { error?: string; errors?: DSQLErrorObject[]; config?: ConnectionConfig };
/**
* # Run Query From MySQL Connection
@@ -19,9 +20,9 @@ type Return<ReturnType = any> =
*/
export default async function connDbHandler<ReturnType = any>(
/**
* ServerlessMySQL Connection Object
* MariaDB Connection Pool Object
*/
conn?: ServerlessMysql,
connPool?: Pool,
/**
* String Or `ConnDBHandlerQueryObject` Array
*/
@@ -33,13 +34,13 @@ export default async function connDbHandler<ReturnType = any>(
debug?: boolean
): Promise<Return<ReturnType>> {
try {
if (!conn) throw new Error("No Connection Found!");
if (!connPool) throw new Error("No Connection Found!");
if (!query) throw new Error("Query String Required!");
let queryErrorArray: DSQLErrorObject[] = [];
if (typeof query == "string") {
const res = await conn.query(trimQuery(query), values);
const res = await connPool.query(trimQuery(query), values);
if (debug) {
debugLog({
@@ -49,7 +50,11 @@ export default async function connDbHandler<ReturnType = any>(
});
}
return JSON.parse(JSON.stringify(res));
if (Array.isArray(res)) {
return Array.from(res);
}
return res;
} else if (typeof query == "object") {
const resArray = [];
@@ -62,7 +67,7 @@ export default async function connDbHandler<ReturnType = any>(
currentQueryError.sql = queryObj.query;
currentQueryError.sqlValues = queryObj.values;
const queryObjRes = await conn.query(
const queryObjRes = await connPool.query(
trimQuery(queryObj.query),
queryObj.values
);
@@ -75,7 +80,11 @@ export default async function connDbHandler<ReturnType = any>(
});
}
resArray.push(JSON.parse(JSON.stringify(queryObjRes)));
if (Array.isArray(queryObjRes)) {
resArray.push(Array.from(queryObjRes));
} else {
resArray.push(queryObjRes);
}
} catch (error: any) {
global.ERROR_CALLBACK?.(
`Connection DB Handler Query Error`,
@@ -101,7 +110,7 @@ export default async function connDbHandler<ReturnType = any>(
};
}
return resArray as any;
return resArray;
} else {
return null;
}
@@ -118,12 +127,13 @@ export default async function connDbHandler<ReturnType = any>(
return {
error: `Connection DB Handler Error: ${error.message}`,
// config: conn,
};
} finally {
conn?.end();
connPool?.end();
}
}
function trimQuery(query: string) {
return query.replace(/\n/gm, "").replace(/ {2,}/g, "").trim();
return query.replace(/\n/gm, " ").replace(/ {2,}/g, " ").trim();
}