datasquirel/package-shared/functions/backend/grabSchemaFieldsFromData.js

95 lines
2.9 KiB
JavaScript
Raw Normal View History

2024-12-08 08:58:57 +00:00
// @ts-check
const serverError = require("./serverError");
/**
* # Add User Table to Database
*
* @param {object} params
* @param {Object<string,any>} [params.data]
* @param {string[]} [params.fields]
* @param {Object<string,any>} [params.excludeData]
* @param {import("../../types").DSQL_FieldSchemaType[]} [params.excludeFields]
*
* @returns {import("../../types").DSQL_FieldSchemaType[]} new user auth object payload
*/
module.exports = function grabSchemaFieldsFromData({
data,
fields,
excludeData,
excludeFields,
}) {
try {
const possibleFields = require("../../data/possibleFields.json");
const dataTypes = require("../../data/dataTypes.json");
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
const finalFields = [];
/** @type {string[]} */
let filteredFields = [];
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 =
/** @type {import("../../types").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(
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
fieldName: fld,
dataType: "INT",
})
);
} else {
finalFields.push(
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
fieldName: fld,
dataType: "VARCHAR(255)",
})
);
}
});
return finalFields;
} catch (/** @type {any} */ error) {
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
serverError({
component: "grabSchemaFieldsFromData.js",
message: error.message,
});
return [];
}
};