datasquirel/package-shared/shell/utils/dbHandler.ts

108 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
import fs from "fs";
import path from "path";
2024-12-06 10:31:24 +00:00
2025-01-10 19:10:28 +00:00
import mysql from "serverless-mysql";
import grabDbSSL from "../../utils/backend/grabDbSSL";
2024-12-06 10:31:24 +00:00
let connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
2025-01-10 19:10:28 +00:00
type Param = {
query: string;
values?: string[] | object;
database?: string;
};
2024-12-06 10:31:24 +00:00
/**
* # Main DB Handler Function
*/
2025-01-10 19:10:28 +00:00
export default async function dbHandler({
query,
values,
database,
}: Param): Promise<any[] | object | null> {
2024-12-06 10:31:24 +00:00
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
let isDbCorrect = true;
if (database) {
connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: database,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
}
if (!isDbCorrect) {
console.log(
"Shell Db Handler ERROR in switching Database! Operation Failed!"
);
return null;
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (query && values) {
results = await connection.query(query, values);
} else {
results = await connection.query(query);
}
/** ********************* Clean up */
await connection.end();
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-06 10:31:24 +00:00
if (process.env.FIRST_RUN) {
return null;
}
console.log("ERROR in dbHandler =>", error.message);
console.log(error);
console.log(connection.config());
fs.appendFileSync(
path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
"utf8"
);
results = null;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return JSON.parse(JSON.stringify(results));
} else {
return null;
}
2025-01-10 19:10:28 +00:00
}