dsql-admin/dsql-app/package-shared/utils/db/conn-db-handler.ts

69 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-01-13 08:00:21 +00:00
import { ServerlessMysql } from "serverless-mysql";
type QueryObject = {
query: string;
values?: (string | number | undefined)[];
};
type Return<ReturnType = any> = ReturnType | null;
/**
* # Run Query From MySQL Connection
* @description Run a query from a pre-existing MySQL/Mariadb Connection
* setup with `serverless-mysql` npm module
*/
export default async function connDbHandler<ReturnType = any>(
/**
* ServerlessMySQL Connection Object
*/
2025-01-28 18:43:16 +00:00
conn?: ServerlessMysql,
2025-01-13 08:00:21 +00:00
/**
* String Or `QueryObject` Array
*/
2025-01-28 18:43:16 +00:00
query?: QueryObject["query"] | QueryObject[],
2025-01-13 08:00:21 +00:00
/**
* Array of Values to Sanitize and Inject
*/
values?: QueryObject["values"]
): Promise<Return<ReturnType>> {
try {
2025-01-28 18:43:16 +00:00
if (!conn) throw new Error("No Connection Found!");
if (!query) throw new Error("Query String Required!");
2025-01-13 08:00:21 +00:00
if (typeof query == "string") {
const res = await conn.query(trimQuery(query), values);
return JSON.parse(JSON.stringify(res));
} else if (typeof query == "object") {
const resArray = [];
for (let i = 0; i < query.length; i++) {
try {
const queryObj = query[i];
const queryObjRes = await conn.query(
trimQuery(queryObj.query),
queryObj.values
);
resArray.push(JSON.parse(JSON.stringify(queryObjRes)));
2025-01-28 18:43:16 +00:00
} catch (error: any) {
console.log(`connDbHandler Query Error: ${error.message}`);
2025-01-13 08:00:21 +00:00
resArray.push(null);
}
}
return resArray as any;
} else {
return null;
}
2025-01-28 18:43:16 +00:00
} catch (error: any) {
console.log(`connDbHandler Error: ${error.message}`);
2025-02-12 16:56:44 +00:00
console.log(conn?.config());
2025-01-13 08:00:21 +00:00
return null;
} finally {
2025-01-28 18:43:16 +00:00
conn?.end();
2025-01-13 08:00:21 +00:00
}
}
function trimQuery(query: string) {
return query.replace(/\n/gm, "").replace(/ {2,}/g, "").trim();
}