datasquirel/package-shared/utils/backend/global-db/DSQL_USER_DB_HANDLER.ts
2025-01-10 20:10:28 +01:00

125 lines
3.7 KiB
TypeScript

// @ts-check
import fs from "fs";
import path from "path";
import mysql from "serverless-mysql";
import grabDbSSL from "../grabDbSSL";
let DSQL_USER = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_READ_ONLY_USERNAME,
password: process.env.DSQL_DB_READ_ONLY_PASSWORD,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
type Param = {
paradigm: "Full Access" | "FA" | "Read Only";
database: string;
queryString: string;
queryValues?: string[];
};
/**
* # DSQL user read-only DB handler
*/
export default function DSQL_USER_DB_HANDLER({
paradigm,
database,
queryString,
queryValues,
}: Param) {
try {
return new Promise((resolve, reject) => {
const fullAccess = paradigm?.match(/full.access|^fa$/i)
? true
: false;
try {
if (fullAccess) {
DSQL_USER = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_FULL_ACCESS_USERNAME,
password: process.env.DSQL_DB_FULL_ACCESS_PASSWORD,
database: database,
ssl: grabDbSSL(),
},
});
} else {
DSQL_USER = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_READ_ONLY_USERNAME,
password: process.env.DSQL_DB_READ_ONLY_PASSWORD,
database: database,
ssl: grabDbSSL(),
},
});
}
/**
* ### Run query Function
* @param {any} results
*/
function runQuery(results: any) {
DSQL_USER.end();
resolve(JSON.parse(JSON.stringify(results)));
}
/**
* ### Query Error
* @param {any} err
*/
function queryError(err: any) {
DSQL_USER.end();
resolve({
error: err.message,
queryStringGenerated: queryString,
queryValuesGenerated: queryValues,
sql: err.sql,
});
}
if (
queryValues &&
Array.isArray(queryValues) &&
queryValues[0]
) {
DSQL_USER.query(queryString, queryValues)
.then(runQuery)
.catch(queryError);
} else {
DSQL_USER.query(queryString)
.then(runQuery)
.catch(queryError);
}
////////////////////////////////////////
} catch (/** @type {any} */ error: any) {
////////////////////////////////////////
fs.appendFileSync(
"./.tmp/dbErrorLogs.txt",
error.message + "\n" + Date() + "\n\n\n",
"utf8"
);
resolve({
error: error.message,
});
}
});
} catch (/** @type {any} */ error: any) {
return {
success: false,
error: error.message,
};
}
}
module.exports = DSQL_USER_DB_HANDLER;