datasquirel/package-shared/functions/api/query/post.ts

103 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
import _ from "lodash";
import serverError from "../../backend/serverError";
import runQuery from "../../backend/db/runQuery";
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";
2024-12-06 10:31:24 +00:00
2025-01-10 19:10:28 +00:00
type Param = {
query: any;
queryValues?: (string | number)[];
dbFullName: string;
tableName?: string;
dbSchema?: DSQL_DatabaseSchemaType;
useLocal?: boolean;
};
2024-12-06 10:31:24 +00:00
/**
* # Post Function For API
*/
2025-01-10 19:10:28 +00:00
export default async function apiPost({
2024-12-06 10:31:24 +00:00
query,
dbFullName,
queryValues,
tableName,
dbSchema,
2024-12-06 11:55:03 +00:00
useLocal,
2025-01-10 19:10:28 +00:00
}: Param): Promise<PostReturn> {
2024-12-06 10:31:24 +00:00
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
if (
typeof query === "object" &&
query?.action?.match(/^create |^alter |^drop /i)
) {
return { success: false, msg: "Wrong Input" };
}
/** @type {any} */
2025-01-10 19:10:28 +00:00
let results: any;
2024-12-06 10:31:24 +00:00
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
2024-12-06 11:55:03 +00:00
local: useLocal,
2024-12-06 10:31:24 +00:00
});
results = result;
if (error) throw error;
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
2025-01-10 19:10:28 +00:00
let tableSchema:
| import("../../../types").DSQL_TableSchemaType
| undefined;
2024-12-06 10:31:24 +00:00
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;
2025-01-10 19:10:28 +00:00
2024-12-06 10:31:24 +00:00
tableSchema = clonedTargetTable;
}
}
return {
success: true,
payload: results,
error: error,
schema: tableName && tableSchema ? tableSchema : undefined,
};
2025-01-10 19:10:28 +00:00
} catch (error: any) {
2024-12-06 10:31:24 +00:00
serverError({
component: "/api/query/post/lines-132-142",
message: error.message,
});
return {
success: false,
payload: results,
error: error.message,
};
}
2025-01-10 19:10:28 +00:00
}