datasquirel/package-shared/functions/backend/db/updateDbEntry.js

207 lines
6.4 KiB
JavaScript
Raw Permalink Normal View History

2023-09-21 14:00:04 +00:00
// @ts-check
/**
* Imports: Handle imports
*/
2024-11-06 06:26:23 +00:00
const sanitizeHtml = require("sanitize-html");
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
2024-12-06 10:31:24 +00:00
const encrypt = require("../../dsql/encrypt");
2024-12-06 11:55:03 +00:00
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
2023-09-21 14:00:04 +00:00
/**
* Update DB Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
* or "Dsql User". Defaults to "Master"
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
* "Read only" or "Full Access"? Defaults to "Read Only"
2024-11-06 06:26:23 +00:00
* @param {string} [params.dbFullName] - Database full name
2023-09-21 14:00:04 +00:00
* @param {string} params.tableName - Table name
2024-11-06 06:26:23 +00:00
* @param {string} [params.encryptionKey]
* @param {string} [params.encryptionSalt]
* @param {any} params.data - Data to add
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
2023-09-21 14:00:04 +00:00
* @param {string} params.identifierColumnName - Update row identifier column name
* @param {string | number} params.identifierValue - Update row identifier column value
2024-12-06 11:55:03 +00:00
* @param {boolean} [params.useLocal]
2023-09-21 14:00:04 +00:00
*
* @returns {Promise<object|null>}
*/
2024-10-14 06:49:01 +00:00
async function updateDbEntry({
dbContext,
paradigm,
dbFullName,
tableName,
data,
tableSchema,
identifierColumnName,
identifierValue,
encryptionKey,
encryptionSalt,
2024-12-06 11:55:03 +00:00
useLocal,
2024-10-14 06:49:01 +00:00
}) {
2023-09-21 14:00:04 +00:00
/**
* Check if data is valid
*/
if (!data || !Object.keys(data).length) return null;
2024-12-09 11:45:39 +00:00
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
2024-11-06 06:26:23 +00:00
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false
: true;
/** @type {(a1:any, a2?:any)=> any } */
2024-12-06 11:55:03 +00:00
const dbHandler = useLocal
? LOCAL_DB_HANDLER
: isMaster
? DB_HANDLER
: DSQL_USER_DB_HANDLER;
2024-11-06 06:26:23 +00:00
2023-09-21 14:00:04 +00:00
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Declare variables
*
* @description Declare "results" variable
*/
const dataKeys = Object.keys(data);
let updateKeyValueArray = [];
let updateValues = [];
for (let i = 0; i < dataKeys.length; i++) {
try {
const dataKey = dataKeys[i];
2024-11-06 06:26:23 +00:00
// @ts-ignore
2023-09-21 14:00:04 +00:00
let value = data[dataKey];
2024-10-14 06:49:01 +00:00
const targetFieldSchemaArray = tableSchema
? tableSchema?.fields?.filter(
(field) => field.fieldName === dataKey
)
: null;
const targetFieldSchema =
targetFieldSchemaArray && targetFieldSchemaArray[0]
? targetFieldSchemaArray[0]
: null;
2023-09-21 14:00:04 +00:00
2024-11-06 06:26:23 +00:00
if (value == null || value == undefined) continue;
2024-12-12 04:59:14 +00:00
const htmlRegex = /<[^>]+>/g;
if (targetFieldSchema?.richText || String(value).match(htmlRegex)) {
2024-11-06 06:26:23 +00:00
value = sanitizeHtml(value, sanitizeHtmlOptions);
}
2023-09-21 14:00:04 +00:00
if (targetFieldSchema?.encrypted) {
2024-12-06 10:31:24 +00:00
value = encrypt({
data: value,
encryptionKey,
encryptionSalt,
});
2023-09-21 14:00:04 +00:00
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
if (targetFieldSchema?.pattern) {
2024-10-14 06:49:01 +00:00
const pattern = new RegExp(
targetFieldSchema.pattern,
targetFieldSchema.patternFlags || ""
);
2024-11-06 06:26:23 +00:00
if (!pattern.test(value)) {
2023-09-21 14:00:04 +00:00
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
2024-11-06 06:26:23 +00:00
if (typeof value === "string" && value.match(/^null$/i)) {
2023-09-21 14:00:04 +00:00
value = {
toSqlString: function () {
return "NULL";
},
};
}
2024-11-06 06:26:23 +00:00
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
2023-09-21 14:00:04 +00:00
updateKeyValueArray.push(`\`${dataKey}\`=?`);
2024-11-06 06:26:23 +00:00
if (typeof value == "number") {
updateValues.push(String(value));
} else {
updateValues.push(value);
}
2023-09-21 14:00:04 +00:00
////////////////////////////////////////
////////////////////////////////////////
2024-11-06 06:26:23 +00:00
} catch (/** @type {any} */ error) {
2023-09-21 14:00:04 +00:00
////////////////////////////////////////
////////////////////////////////////////
2024-10-14 06:49:01 +00:00
console.log(
"DSQL: Error in parsing data keys in update function =>",
error.message
);
2023-09-21 14:00:04 +00:00
continue;
}
}
////////////////////////////////////////
////////////////////////////////////////
updateKeyValueArray.push(`date_updated='${Date()}'`);
updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
////////////////////////////////////////
////////////////////////////////////////
2024-10-14 06:49:01 +00:00
const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(
","
)} WHERE \`${identifierColumnName}\`=?`;
2023-09-21 14:00:04 +00:00
updateValues.push(identifierValue);
2024-11-06 06:26:23 +00:00
const updatedEntry = isMaster
? await dbHandler(query, updateValues)
: await dbHandler({
paradigm,
database: dbFullName,
queryString: query,
queryValues: updateValues,
});
2023-09-21 14:00:04 +00:00
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return updatedEntry;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = updateDbEntry;