datasquirel/package-shared/functions/backend/db/grab-parsed-value.ts
2025-12-11 09:18:22 +01:00

101 lines
2.5 KiB
TypeScript

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): string | number | undefined {
let newValue = value as string | number | undefined;
const targetFieldSchema = tableSchema
? tableSchema?.fields?.find((field) => field.fieldName === dataKey)
: null;
if (typeof newValue == "undefined") {
return;
}
if (
typeof newValue !== "string" &&
typeof newValue !== "number" &&
!newValue
) {
return;
}
if (typeof newValue == "object" && !newValue) {
return;
}
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(/./)
) {
newValue = "";
}
if (targetFieldSchema?.encrypted) {
newValue =
encrypt({
data: newValue.toString(),
encryptionKey,
encryptionSalt,
}) || undefined;
}
if (typeof newValue === "object") {
newValue = JSON.stringify(newValue);
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(
targetFieldSchema.pattern,
targetFieldSchema.patternFlags || ""
);
if (typeof newValue == "string" && !pattern.test(newValue)) {
console.log("DSQL: Pattern not matched =>", newValue);
newValue = "";
}
}
if (
typeof newValue === "string" &&
(newValue.match(/^null$/i) || !newValue.match(/./i))
) {
newValue = undefined;
}
if (
typeof newValue === "boolean" ||
targetFieldSchema?.dataType?.match(/boolean/i)
) {
newValue = newValue ? 1 : 0;
}
return newValue;
}