datasquirel/package-shared/functions/api/query/get.js

96 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

2024-12-06 10:31:24 +00:00
// @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]
2024-12-06 11:55:03 +00:00
* @param {boolean} [params.useLocal]
2024-12-06 10:31:24 +00:00
*
* @returns {Promise<import("../../../types").GetReturn>}
*/
module.exports = async function apiGet({
query,
dbFullName,
queryValues,
tableName,
dbSchema,
2024-12-06 11:55:03 +00:00
useLocal,
2024-12-06 10:31:24 +00:00
}) {
if (
typeof query == "string" &&
2024-12-08 08:58:57 +00:00
query.match(/^alter|^delete|information_schema|databases|^create/i)
2024-12-06 10:31:24 +00:00
) {
2024-12-08 08:58:57 +00:00
return { success: false, msg: "Wrong Input." };
2024-12-06 10:31:24 +00:00
}
/**
* 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,
2024-12-06 11:55:03 +00:00
local: useLocal,
2024-12-06 10:31:24 +00:00
});
/** @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 };
}
};