import sanitizeHtml from "sanitize-html";
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
import encrypt from "../../dsql/encrypt";
import { DSQL_TableSchemaType } from "../../../types";
import _ from "lodash";
type Param = {
value?: any;
tableSchema?: DSQL_TableSchemaType;
encryptionKey?: string;
encryptionSalt?: string;
dataKey: string;
};
/**
* # Update DB Function
* @description
*/
export default function grabParsedValue({
value,
tableSchema,
encryptionKey,
encryptionSalt,
dataKey,
}: Param): any {
let newValue = value;
const targetFieldSchemaArray = tableSchema
? tableSchema?.fields?.filter((field) => field.fieldName === dataKey)
: null;
const targetFieldSchema =
targetFieldSchemaArray && targetFieldSchemaArray[0]
? targetFieldSchemaArray[0]
: null;
if (typeof newValue == "undefined") return;
if (typeof newValue == "object" && !newValue) newValue = "";
const htmlRegex = /<[^>]+>/g;
if (targetFieldSchema?.richText || String(newValue).match(htmlRegex)) {
newValue = sanitizeHtml(newValue, sanitizeHtmlOptions);
}
if (
targetFieldSchema?.dataType?.match(/int$/i) &&
typeof value == "string" &&
!value?.match(/./)
) {
value = "";
}
if (targetFieldSchema?.encrypted) {
newValue = encrypt({
data: newValue,
encryptionKey,
encryptionSalt,
});
}
if (typeof newValue === "object") {
newValue = JSON.stringify(newValue);
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(
targetFieldSchema.pattern,
targetFieldSchema.patternFlags || ""
);
if (!pattern.test(newValue)) {
console.log("DSQL: Pattern not matched =>", newValue);
newValue = "";
}
}
if (typeof newValue === "string" && newValue.match(/^null$/i)) {
newValue = {
toSqlString: function () {
return "NULL";
},
};
}
if (typeof newValue === "string" && !newValue.match(/./i)) {
newValue = {
toSqlString: function () {
return "NULL";
},
};
}
return newValue;
}