datasquirel/engine/db/query.js

87 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-07-07 14:08:38 +00:00
/**
* Imports: Handle imports
*/
/**
* RAW Query DB Function
* ==============================================================================
* @description Description
2023-07-07 14:52:24 +00:00
* @async
2023-07-07 14:08:38 +00:00
*
* @param {object} params - An object containing the function parameters.
* @param {string} params.dbFullName - Database full name
* @param {string?} params.dbHost - Database host
* @param {string?} params.dbPassword - Database password
* @param {string?} params.dbUsername - Database username
* @param {string?} params.query - Query string
2023-07-08 06:15:25 +00:00
* @param {string[]?} params.valuesArray - Values array
2023-07-07 14:08:38 +00:00
*
2023-07-07 14:52:24 +00:00
* @returns {Promise<object|null>}
2023-07-07 14:08:38 +00:00
*/
2023-07-08 06:15:25 +00:00
async function query({ dbFullName, dbHost, dbPassword, dbUsername, query, valuesArray }) {
2023-07-07 14:08:38 +00:00
/**
2023-07-08 06:15:25 +00:00
* Initialize mysql
2023-07-07 14:08:38 +00:00
*/
const mysql = require("serverless-mysql")({
config: {
host: dbHost,
user: dbUsername,
password: dbPassword,
database: dbFullName.toString().replace(/[^a-z0-9\_\-]/g, ""),
charset: "utf8mb4",
},
});
let results;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
try {
/**
* Run Query
*/
2023-07-08 06:15:25 +00:00
if (valuesArray && Array.isArray(valuesArray) && valuesArray[0]) {
results = await mysql.query(query, valuesArray);
} else {
results = await mysql.query(query);
}
2023-07-07 14:08:38 +00:00
/**
* Clean up
*/
await mysql.end();
} catch (error) {
/**
* Handle error and clean up
*/
2023-07-08 06:38:59 +00:00
console.log("\x1b[31mDSQL Database Handler ERROR\x1b[0m =>", dbFullName, error.message);
2023-07-07 14:08:38 +00:00
/**
* Clean up
*/
await mysql.end();
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
if (results) {
return JSON.parse(JSON.stringify(results));
} else {
console.log("\x1b[31mDSQL RAW Database Handler No results returned\x1b[0m =>", results);
return null;
}
2023-07-07 19:13:13 +00:00
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = query;