datasquirel/package-shared/functions/backend/grabSchemaFieldsFromData.ts
2025-01-10 20:10:28 +01:00

88 lines
2.5 KiB
TypeScript
Executable File

import { DSQL_FieldSchemaType } from "../../types";
import serverError from "./serverError";
type Param = {
data?: { [s: string]: any };
fields?: string[];
excludeData?: { [s: string]: any };
excludeFields?: DSQL_FieldSchemaType[];
};
/**
* # Add User Table to Database
*/
export default function grabSchemaFieldsFromData({
data,
fields,
excludeData,
excludeFields,
}: Param): DSQL_FieldSchemaType[] {
try {
const possibleFields = require("../../data/possibleFields.json");
const dataTypes = require("../../data/dataTypes.json");
/** @type {DSQL_FieldSchemaType[]} */
const finalFields: DSQL_FieldSchemaType[] = [];
/** @type {string[]} */
let filteredFields: string[] = [];
if (data && Object.keys(data)?.[0]) {
filteredFields = Object.keys(data);
}
if (fields) {
filteredFields = [...filteredFields, ...fields];
filteredFields = [...new Set(filteredFields)];
}
filteredFields = filteredFields
.filter(
(fld) => !excludeData || !Object.keys(excludeData).includes(fld)
)
.filter(
(fld) =>
!excludeFields ||
!excludeFields.find((exlFld) => exlFld.fieldName == fld)
);
filteredFields.forEach((fld) => {
const value = data ? data[fld] : null;
if (typeof value == "string") {
const newField: DSQL_FieldSchemaType = {
fieldName: fld,
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
};
if (Boolean(value.match(/<[^>]+>/g))) {
newField.richText = true;
}
finalFields.push(newField);
} else if (typeof value == "number") {
finalFields.push({
fieldName: fld,
dataType: "INT",
});
} else {
finalFields.push({
fieldName: fld,
dataType: "VARCHAR(255)",
});
}
});
return finalFields;
} catch (/** @type {any} */ error: any) {
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
serverError({
component: "grabSchemaFieldsFromData.js",
message: error.message,
});
return [];
}
}