datasquirel/package-shared/functions/api/query/get.js
Benjamin Toby 8ca2779741 Updates
2024-12-06 11:31:24 +01:00

94 lines
2.6 KiB
JavaScript

// @ts-check
const _ = require("lodash");
const serverError = require("../../backend/serverError");
const runQuery = require("../../backend/db/runQuery");
/**
* # Get Function FOr API
*
* @param {object} params
* @param {string} params.query
* @param {(string|number)[]} [params.queryValues]
* @param {string} params.dbFullName
* @param {string} [params.tableName]
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
*
* @returns {Promise<import("../../../types").GetReturn>}
*/
module.exports = async function apiGet({
query,
dbFullName,
queryValues,
tableName,
dbSchema,
}) {
if (
typeof query == "string" &&
(query.match(/^alter|^delete|information_schema|databases|^create/i) ||
!query.match(/^select/i))
) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
let results;
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
queryValuesArray: queryValues,
readOnly: true,
dbSchema,
tableName,
});
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
let tableSchema;
if (dbSchema) {
const targetTable = dbSchema.tables.find(
(table) => table.tableName === tableName
);
if (targetTable) {
const clonedTargetTable = _.cloneDeep(targetTable);
delete clonedTargetTable.childTable;
delete clonedTargetTable.childTableDbFullName;
delete clonedTargetTable.childTableName;
delete clonedTargetTable.childrenTables;
delete clonedTargetTable.updateData;
delete clonedTargetTable.tableNameOld;
delete clonedTargetTable.indexes;
tableSchema = clonedTargetTable;
}
}
if (error) throw error;
if (result.error) throw new Error(result.error);
results = result;
/** @type {import("../../../types").GetReturn} */
const resObject = {
success: true,
payload: results,
schema: tableName && tableSchema ? tableSchema : undefined,
};
return resObject;
} catch (/** @type {any} */ error) {
serverError({
component: "/api/query/get/lines-85-94",
message: error.message,
});
return { success: false, payload: null, error: error.message };
}
};