dsql-admin/dsql-app/package-shared/functions/backend/dbHandler.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-01-13 08:00:21 +00:00
import fs from "fs";
import serverError from "./serverError";
2025-01-14 15:27:08 +00:00
import mysql from "serverless-mysql";
import grabDSQLConnection from "../../utils/grab-dsql-connection";
2025-01-13 08:00:21 +00:00
/**
* # Main DB Handler Function
*/
export default async function dbHandler(...args: any[]) {
process.env.NODE_ENV?.match(/dev/) &&
fs.appendFileSync(
"./.tmp/sqlQuery.sql",
args[0] + "\n" + Date() + "\n\n\n",
"utf8"
);
2025-01-14 15:27:08 +00:00
const CONNECTION = grabDSQLConnection();
2025-01-13 08:00:21 +00:00
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
results = await new Promise((resolve, reject) => {
2025-01-14 15:27:08 +00:00
CONNECTION.query(
2025-01-13 08:00:21 +00:00
...args,
(error: any, result: any, fields: any) => {
if (error) {
resolve({ error: error.message });
} else {
resolve(result);
}
}
);
});
} catch (error: any) {
fs.appendFileSync(
"./.tmp/dbErrorLogs.txt",
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
"utf8"
);
results = null;
serverError({
component: "dbHandler",
message: error.message,
});
2025-01-14 15:27:08 +00:00
} finally {
await CONNECTION?.end();
2025-01-13 08:00:21 +00:00
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return JSON.parse(JSON.stringify(results));
} else {
return null;
}
}