datasquirel/package-shared/functions/backend/dbHandler.ts
2025-01-10 20:10:28 +01:00

82 lines
2.0 KiB
TypeScript

import fs from "fs";
import serverError from "./serverError";
import mysql from "serverless-mysql";
import grabDbSSL from "../../utils/backend/grabDbSSL";
const 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(),
},
});
/**
* # 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"
);
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
results = await new Promise((resolve, reject) => {
connection.query(
...args,
(error: any, result: any, fields: any) => {
if (error) {
resolve({ error: error.message });
} else {
resolve(result);
}
}
);
});
await connection.end();
} 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,
});
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return JSON.parse(JSON.stringify(results));
} else {
return null;
}
}