208 lines
10 KiB
JavaScript
208 lines
10 KiB
JavaScript
"use strict";
|
|
// @ts-check
|
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
return new (P || (P = Promise))(function (resolve, reject) {
|
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
});
|
|
};
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = addDbEntry;
|
|
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
|
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
|
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
|
|
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
|
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
|
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
|
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
|
/**
|
|
* Add a db Entry 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"
|
|
* @param {string} [params.dbFullName] - Database full name
|
|
* @param {string} params.tableName - Table name
|
|
* @param {any} params.data - Data to add
|
|
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
|
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
|
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
|
* @param {boolean} [params.update] - Update this row if it exists
|
|
* @param {string} [params.encryptionKey] - Update this row if it exists
|
|
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
|
* @param {boolean} [params.useLocal]
|
|
*
|
|
* @returns {Promise<any>}
|
|
*/
|
|
function addDbEntry(_a) {
|
|
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }) {
|
|
var _b, _c;
|
|
/**
|
|
* Initialize variables
|
|
*/
|
|
const isMaster = useLocal
|
|
? true
|
|
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
|
? false
|
|
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
|
? false
|
|
: true;
|
|
/** @type { any } */
|
|
const dbHandler = useLocal
|
|
? LOCAL_DB_HANDLER_1.default
|
|
: isMaster
|
|
? DB_HANDLER_1.default
|
|
: DSQL_USER_DB_HANDLER_1.default;
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
if (data === null || data === void 0 ? void 0 : data["date_created_timestamp"])
|
|
delete data["date_created_timestamp"];
|
|
if (data === null || data === void 0 ? void 0 : data["date_updated_timestamp"])
|
|
delete data["date_updated_timestamp"];
|
|
if (data === null || data === void 0 ? void 0 : data["date_updated"])
|
|
delete data["date_updated"];
|
|
if (data === null || data === void 0 ? void 0 : data["date_updated_code"])
|
|
delete data["date_updated_code"];
|
|
if (data === null || data === void 0 ? void 0 : data["date_created"])
|
|
delete data["date_created"];
|
|
if (data === null || data === void 0 ? void 0 : data["date_created_code"])
|
|
delete data["date_created_code"];
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
/**
|
|
* Handle function logic
|
|
*/
|
|
if (duplicateColumnName && typeof duplicateColumnName === "string") {
|
|
const duplicateValue = isMaster
|
|
? yield dbHandler(`SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`, [duplicateColumnValue])
|
|
: yield dbHandler({
|
|
paradigm: "Read Only",
|
|
queryString: `SELECT * FROM \`${dbFullName}\`.\`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
|
queryValues: [duplicateColumnValue],
|
|
});
|
|
if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) {
|
|
return null;
|
|
}
|
|
else if (duplicateValue && duplicateValue[0] && update) {
|
|
return yield (0, updateDbEntry_1.default)({
|
|
dbContext,
|
|
paradigm,
|
|
dbFullName,
|
|
tableName,
|
|
data,
|
|
tableSchema,
|
|
encryptionKey,
|
|
encryptionSalt,
|
|
identifierColumnName: duplicateColumnName,
|
|
identifierValue: duplicateColumnValue || "",
|
|
});
|
|
}
|
|
}
|
|
/**
|
|
* Declare variables
|
|
*
|
|
* @description Declare "results" variable
|
|
*/
|
|
const dataKeys = Object.keys(data);
|
|
let insertKeysArray = [];
|
|
let insertValuesArray = [];
|
|
for (let i = 0; i < dataKeys.length; i++) {
|
|
try {
|
|
const dataKey = dataKeys[i];
|
|
// @ts-ignore
|
|
let value = data === null || data === void 0 ? void 0 : data[dataKey];
|
|
const targetFieldSchemaArray = tableSchema
|
|
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName == dataKey)
|
|
: null;
|
|
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
|
? targetFieldSchemaArray[0]
|
|
: null;
|
|
if (value == null || value == undefined)
|
|
continue;
|
|
if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) &&
|
|
typeof value == "string" &&
|
|
!(value === null || value === void 0 ? void 0 : value.match(/./)))
|
|
continue;
|
|
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
|
value = (0, encrypt_1.default)({
|
|
data: value,
|
|
encryptionKey,
|
|
encryptionSalt,
|
|
});
|
|
console.log("DSQL: Encrypted value =>", value);
|
|
}
|
|
const htmlRegex = /<[^>]+>/g;
|
|
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
|
|
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
|
|
}
|
|
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
|
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
|
if (!pattern.test(value)) {
|
|
console.log("DSQL: Pattern not matched =>", value);
|
|
value = "";
|
|
}
|
|
}
|
|
insertKeysArray.push("`" + dataKey + "`");
|
|
if (typeof value === "object") {
|
|
value = JSON.stringify(value);
|
|
}
|
|
if (typeof value == "number") {
|
|
insertValuesArray.push(String(value));
|
|
}
|
|
else {
|
|
insertValuesArray.push(value);
|
|
}
|
|
}
|
|
catch ( /** @type {any} */error) {
|
|
console.log("DSQL: Error in parsing data keys =>", error.message);
|
|
continue;
|
|
}
|
|
}
|
|
////////////////////////////////////////
|
|
if (!(data === null || data === void 0 ? void 0 : data["date_created"])) {
|
|
insertKeysArray.push("`date_created`");
|
|
insertValuesArray.push(Date());
|
|
}
|
|
if (!(data === null || data === void 0 ? void 0 : data["date_created_code"])) {
|
|
insertKeysArray.push("`date_created_code`");
|
|
insertValuesArray.push(Date.now());
|
|
}
|
|
////////////////////////////////////////
|
|
if (!(data === null || data === void 0 ? void 0 : data["date_updated"])) {
|
|
insertKeysArray.push("`date_updated`");
|
|
insertValuesArray.push(Date());
|
|
}
|
|
if (!(data === null || data === void 0 ? void 0 : data["date_updated_code"])) {
|
|
insertKeysArray.push("`date_updated_code`");
|
|
insertValuesArray.push(Date.now());
|
|
}
|
|
////////////////////////////////////////
|
|
const query = `INSERT INTO \`${dbFullName}\`.\`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
|
const queryValuesArray = insertValuesArray;
|
|
const newInsert = isMaster
|
|
? yield dbHandler(query, queryValuesArray)
|
|
: yield dbHandler({
|
|
paradigm,
|
|
queryString: query,
|
|
queryValues: queryValuesArray,
|
|
});
|
|
/**
|
|
* Return statement
|
|
*/
|
|
return newInsert;
|
|
});
|
|
}
|