minor revision
This commit is contained in:
parent
cecdd5e764
commit
ab6a09558c
@ -1,7 +1,5 @@
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const imageInputFileToBase64 = require("./media/imageInputFileToBase64");
|
||||
const imageInputToBase64 = require("./media/imageInputToBase64");
|
||||
@ -9,17 +7,12 @@ const inputFileToBase64 = require("./media/inputFileToBase64");
|
||||
const getAccessToken = require("./auth/google/getAccessToken");
|
||||
const logout = require("./auth/logout");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Media Functions Object
|
||||
* ==============================================================================
|
||||
*/
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64,
|
||||
@ -28,9 +21,7 @@ const media = {
|
||||
};
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Media Functions Object
|
||||
* ==============================================================================
|
||||
* User Auth Object
|
||||
*/
|
||||
const auth = {
|
||||
google: {
|
||||
@ -40,9 +31,7 @@ const auth = {
|
||||
};
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Export
|
||||
* ==============================================================================
|
||||
*/
|
||||
const datasquirelClient = {
|
||||
media: media,
|
||||
@ -50,7 +39,3 @@ const datasquirelClient = {
|
||||
};
|
||||
|
||||
module.exports = datasquirelClient;
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
@ -1,163 +0,0 @@
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
|
||||
const encrypt = require("../../functions/encrypt");
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../utils/sanitizeHtmlOptions");
|
||||
const dsqlDbHandler = require("../utils/dsqlDbHandler");
|
||||
const updateDb = require("./updateDb");
|
||||
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} params.dbFullName - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {object} params.data - Data to add
|
||||
* @param {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.dbHost - Database host
|
||||
* @param {string?} params.dbPassword - Database password
|
||||
* @param {string?} params.dbUsername - Database username
|
||||
* @param {string?} params.encryptionKey - Encryption key
|
||||
* @param {string?} params.encryptionSalt - Encryption salt
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function addDb({ dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, dbHost, dbPassword, dbUsername, encryptionKey, encryptionSalt }) {
|
||||
/**
|
||||
* Initialize variables
|
||||
*/
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Handle function logic
|
||||
*/
|
||||
|
||||
if (duplicateColumnName && typeof duplicateColumnName === "string") {
|
||||
const duplicateValue = await dsqlDbHandler({
|
||||
queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
queryValuesArray: [duplicateColumnValue],
|
||||
database: dbFullName,
|
||||
dbHost,
|
||||
dbPassword,
|
||||
dbUsername,
|
||||
});
|
||||
|
||||
if (duplicateValue && duplicateValue[0] && !update) {
|
||||
return null;
|
||||
} else if (duplicateValue && duplicateValue[0] && update) {
|
||||
return await updateDb({
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
identifierColumnName: duplicateColumnName,
|
||||
identifierValue: duplicateColumnValue,
|
||||
dbHost,
|
||||
dbPassword,
|
||||
dbUsername,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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];
|
||||
let value = data[dataKey];
|
||||
|
||||
const targetFieldSchemaArray = tableSchema ? tableSchema?.fields?.filter((field) => field.fieldName === dataKey) : null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0] ? targetFieldSchemaArray[0] : null;
|
||||
|
||||
if (!value) continue;
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt({ data: value, encryptionKey, encryptionSalt });
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.richText) {
|
||||
value = sanitizeHtml(value, sanitizeHtmlOptions);
|
||||
}
|
||||
|
||||
insertKeysArray.push("`" + dataKey + "`");
|
||||
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
|
||||
insertValuesArray.push(value);
|
||||
} catch (error) {
|
||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
|
||||
insertKeysArray.push("`date_created`");
|
||||
insertValuesArray.push(Date());
|
||||
|
||||
insertKeysArray.push("`date_created_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
|
||||
/** ********************************************** */
|
||||
|
||||
insertKeysArray.push("`date_updated`");
|
||||
insertValuesArray.push(Date());
|
||||
|
||||
insertKeysArray.push("`date_updated_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
|
||||
/** ********************************************** */
|
||||
|
||||
const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
||||
const queryValuesArray = insertValuesArray;
|
||||
|
||||
const newInsert = await dsqlDbHandler({
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValuesArray,
|
||||
dbHost,
|
||||
dbPassword,
|
||||
dbUsername,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return newInsert;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = addDb;
|
@ -1,80 +0,0 @@
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
const dsqlDbHandler = require("../utils/dsqlDbHandler");
|
||||
|
||||
/**
|
||||
* Delete DB Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} params.dbFullName - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {DSQL_TableSchemaType?} params.tableSchema - Table schema
|
||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
||||
* @param {string|number} params.identifierValue - Update row identifier column value
|
||||
* @param {boolean?} params.update - Update this row if it exists
|
||||
* @param {string?} params.dbHost - Database host
|
||||
* @param {string?} params.dbPassword - Database password
|
||||
* @param {string?} params.dbUsername - Database username
|
||||
* @param {string?} params.encryptionKey - Encryption key
|
||||
* @param {string?} params.encryptionSalt - Encryption salt
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function deleteDb({ dbFullName, tableName, identifierColumnName, identifierValue, dbHost, dbPassword, dbUsername, encryptionKey, encryptionSalt }) {
|
||||
try {
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
const deletedEntry = await dsqlDbHandler({
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValuesArray: [identifierValue],
|
||||
dbHost,
|
||||
dbPassword,
|
||||
dbUsername,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = deleteDb;
|
@ -1,91 +0,0 @@
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
|
||||
/**
|
||||
* RAW Query DB Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} params.dbFullName - Database full name
|
||||
* @param {string?} params.dbHost - Database host
|
||||
* @param {string?} params.dbPassword - Database password
|
||||
* @param {string?} params.dbUsername - Database username
|
||||
* @param {string?} params.query - Query string
|
||||
* @param {string[]?} params.valuesArray - Values array
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function query({ dbFullName, dbHost, dbPassword, dbUsername, query, valuesArray }) {
|
||||
/**
|
||||
* Initialize mysql
|
||||
*/
|
||||
const mysql = require("serverless-mysql")({
|
||||
config: {
|
||||
host: dbHost,
|
||||
user: dbUsername,
|
||||
password: dbPassword,
|
||||
database: dbFullName.toString().replace(/[^a-z0-9\_\-]/g, ""),
|
||||
charset: "utf8mb4",
|
||||
},
|
||||
});
|
||||
|
||||
let results;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
try {
|
||||
/**
|
||||
* Run Query
|
||||
*/
|
||||
if (valuesArray && Array.isArray(valuesArray) && valuesArray[0]) {
|
||||
results = await mysql.query(query, valuesArray);
|
||||
} else {
|
||||
results = await mysql.query(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up
|
||||
*/
|
||||
await mysql.end();
|
||||
} catch (error) {
|
||||
/**
|
||||
* Handle error and clean up
|
||||
*/
|
||||
console.log("\x1b[31mDSQL Database Handler ERROR\x1b[0m =>", dbFullName, error.message);
|
||||
|
||||
/**
|
||||
* Clean up
|
||||
*/
|
||||
await mysql.end();
|
||||
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
console.log("\x1b[31mDSQL RAW Database Handler No results returned\x1b[0m =>", results);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = query;
|
@ -1,129 +0,0 @@
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
const encrypt = require("../../functions/encrypt");
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../utils/sanitizeHtmlOptions");
|
||||
const dsqlDbHandler = require("../utils/dsqlDbHandler");
|
||||
|
||||
/**
|
||||
* Update DB Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} params.dbFullName - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {object} params.data - Data to add
|
||||
* @param {DSQL_TableSchemaType?} params.tableSchema - Table schema
|
||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
||||
* @param {string|number} params.identifierValue - Update row identifier column value
|
||||
* @param {boolean?} params.update - Update this row if it exists
|
||||
* @param {string?} params.dbHost - Database host
|
||||
* @param {string?} params.dbPassword - Database password
|
||||
* @param {string?} params.dbUsername - Database username
|
||||
* @param {string?} params.encryptionKey - Encryption key
|
||||
* @param {string?} params.encryptionSalt - Encryption salt
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function updateDb({ dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, dbHost, dbPassword, dbUsername, encryptionKey, encryptionSalt }) {
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
if (!data || !Object.keys(data).length) return null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 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];
|
||||
let value = data[dataKey];
|
||||
|
||||
const targetFieldSchemaArray = tableSchema ? tableSchema?.fields?.filter((field) => field.fieldName === dataKey) : null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0] ? targetFieldSchemaArray[0] : null;
|
||||
|
||||
if (!value) continue;
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt({ data: value, encryptionKey, encryptionSalt });
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.richText) {
|
||||
value = sanitizeHtml(value, sanitizeHtmlOptions);
|
||||
}
|
||||
|
||||
if (typeof value === "string" && value.match(/^null$/i)) value = "";
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (!value && value != 0) continue;
|
||||
|
||||
updateKeyValueArray.push(`\`${dataKey}\`=?`);
|
||||
updateValues.push(value);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
console.log("DSQL: Error in parsing data keys in update function =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
updateKeyValueArray.push(`date_updated='${Date()}'`);
|
||||
updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
updateValues.push(identifierValue);
|
||||
|
||||
const updatedEntry = await dsqlDbHandler({
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValuesArray: updateValues,
|
||||
dbHost,
|
||||
dbPassword,
|
||||
dbUsername,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return updatedEntry;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = updateDb;
|
@ -1,42 +0,0 @@
|
||||
/**
|
||||
* Imports
|
||||
* ===================================
|
||||
*/
|
||||
const addDb = require("./db/addDb");
|
||||
const query = require("./db/query");
|
||||
const update = require("./db/updateDb");
|
||||
const deleteDb = require("./db/deleteDb");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Media Functions Object
|
||||
* ===================================
|
||||
*/
|
||||
const db = {
|
||||
addDb: addDb,
|
||||
updateDb: update,
|
||||
deleteDb: deleteDb,
|
||||
query: query,
|
||||
};
|
||||
|
||||
/**
|
||||
* Main Export
|
||||
* ===================================
|
||||
*/
|
||||
const dsqlEngine = {
|
||||
db: db,
|
||||
};
|
||||
|
||||
// module.exports = dsqlEngine;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
// exports.addDb = dsqlEngine.db.addDb;
|
||||
// exports.updateDb = dsqlEngine.db.updateDb;
|
||||
// exports.deleteDb = dsqlEngine.db.deleteDb;
|
||||
// exports.query = dsqlEngine.db.query;
|
@ -1,163 +0,0 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
/** ********************************************** */
|
||||
|
||||
const dbHandler = require("../functions/backend/dbHandler");
|
||||
const noDatabaseDbHandler = require("../functions/backend/noDatabaseDbHandler");
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
const createTable = require("./utils/createTable");
|
||||
const updateTable = require("./utils/updateTable");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
async function createDbFromSchema({ path }) {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
const dbSchema = require(path);
|
||||
|
||||
for (let i = 0; i < dbSchema.length; i++) {
|
||||
const database = dbSchema[i];
|
||||
const { dbFullName, tables } = database;
|
||||
|
||||
/** ********************************************** */
|
||||
|
||||
// const showDatabases = await noDatabaseDbHandler(`SHOW DATABASES`);
|
||||
const dbCheck = await noDatabaseDbHandler(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`);
|
||||
|
||||
if (dbCheck && dbCheck[0]?.dbFullName) {
|
||||
// Database Exists
|
||||
} else {
|
||||
const newDatabase = await noDatabaseDbHandler(`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
/**
|
||||
* Handle Individual Tables
|
||||
*
|
||||
* @description Handle Individual Tables
|
||||
*/
|
||||
const allTables = await noDatabaseDbHandler(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`);
|
||||
|
||||
let tableDropped;
|
||||
|
||||
for (let tb = 0; tb < allTables.length; tb++) {
|
||||
const { TABLE_NAME } = allTables[tb];
|
||||
|
||||
if (!tables.filter((_table) => _table.tableName === TABLE_NAME)[0]) {
|
||||
const oldTableFilteredArray = tables.filter((_table) => _table.tableNameOld && _table.tableNameOld === TABLE_NAME);
|
||||
|
||||
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
|
||||
console.log("Renaming Table");
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
} else {
|
||||
console.log(`Dropping Table from ${dbFullName}`);
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `DROP TABLE \`${TABLE_NAME}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
tableDropped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
for (let t = 0; t < tables.length; t++) {
|
||||
const table = tables[t];
|
||||
|
||||
if (tableDropped) continue;
|
||||
|
||||
const { tableName, fields, indexes } = table;
|
||||
|
||||
const tableCheck = await varDatabaseDbHandler({
|
||||
queryString: `
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
TABLE_NAME
|
||||
FROM
|
||||
information_schema.TABLES
|
||||
WHERE
|
||||
TABLE_SCHEMA = '${dbFullName}' AND
|
||||
TABLE_NAME = '${table.tableName}'
|
||||
) AS tableExists`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
/** ********************************************** */
|
||||
|
||||
if (tableCheck && tableCheck[0]?.tableExists > 0) {
|
||||
// Update Existing Table
|
||||
const updateExistingTable = await updateTable({
|
||||
dbFullName: dbFullName,
|
||||
tableName: tableName,
|
||||
tableInfoArray: fields,
|
||||
varDatabaseDbHandler,
|
||||
userId,
|
||||
dbSchema,
|
||||
tableIndexes: indexes,
|
||||
});
|
||||
|
||||
if (table.childrenTables && table.childrenTables[0]) {
|
||||
for (let ch = 0; ch < table.childrenTables.length; ch++) {
|
||||
const childTable = table.childrenTables[ch];
|
||||
|
||||
const updateExistingChildTable = await updateTable({
|
||||
dbFullName: childTable.dbNameFull,
|
||||
tableName: childTable.tableName,
|
||||
tableInfoArray: fields,
|
||||
varDatabaseDbHandler,
|
||||
userId,
|
||||
dbSchema,
|
||||
tableIndexes: indexes,
|
||||
clone: true,
|
||||
});
|
||||
|
||||
console.log(updateExistingChildTable);
|
||||
}
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
} else {
|
||||
/** ********************************************** */
|
||||
|
||||
// Create New Table
|
||||
const createNewTable = await createTable({ tableName: tableName, tableInfoArray: fields, varDatabaseDbHandler, dbFullName: dbFullName, dbSchema });
|
||||
}
|
||||
|
||||
/** ********************************************** */
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
const path = process.argv[process.argv.indexOf("--path") + 1];
|
||||
|
||||
createDbFromSchema({ path });
|
@ -1,12 +0,0 @@
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
const defaultFieldsRegexp = /^id$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
|
||||
module.exports = defaultFieldsRegexp;
|
@ -1,99 +0,0 @@
|
||||
const fs = require("fs");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.queryString - SQL string
|
||||
* @param {string[]?} params.queryValuesArray - Values Array
|
||||
* @param {string} params.database - Database name
|
||||
* @param {DSQL_TableSchemaType?} params.tableSchema - Table schema
|
||||
* @param {string} params.dbHost - Database host
|
||||
* @param {string} params.dbUsername - Database username
|
||||
* @param {string} params.dbPassword - Database password
|
||||
* @param {string?} params.encryptionKey - Encryption key
|
||||
* @param {string?} params.encryptionSalt - Encryption salt
|
||||
*
|
||||
* @returns {Promise<object[]|null>}
|
||||
*/
|
||||
async function dsqlDbHandler({ queryString, queryValuesArray, database, tableSchema, dbHost, dbUsername, dbPassword, encryptionKey, encryptionSalt }) {
|
||||
const mysql = require("serverless-mysql")({
|
||||
config: {
|
||||
host: dbHost,
|
||||
user: dbUsername,
|
||||
password: dbPassword,
|
||||
database: database.toString().replace(/[^a-z0-9\_\-]/g, ""),
|
||||
charset: "utf8mb4",
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Check if query values array is an array
|
||||
*/
|
||||
if (!queryString || !queryValuesArray || !Array.isArray(queryValuesArray) || !queryValuesArray[0]) {
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/**
|
||||
* Run Query
|
||||
*/
|
||||
results = await mysql.query(queryString, queryValuesArray);
|
||||
|
||||
/**
|
||||
* Clean up
|
||||
*/
|
||||
await mysql.end();
|
||||
} catch (error) {
|
||||
/**
|
||||
* Handle error and clean up
|
||||
*/
|
||||
console.log("\x1b[31mDSQL Database Handler ERROR\x1b[0m =>", database, error.message);
|
||||
|
||||
/**
|
||||
* Clean up
|
||||
*/
|
||||
await mysql.end();
|
||||
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
try {
|
||||
const unparsedResults = JSON.parse(JSON.stringify(results));
|
||||
const parsedResults = parseDbResults({ unparsedResults: unparsedResults, tableSchema: tableSchema, encryptionKey, encryptionSalt });
|
||||
return parsedResults;
|
||||
} catch (error) {
|
||||
console.log("\x1b[31mDSQL Database Handler ERROR\x1b[0m =>", database, error.message);
|
||||
return null;
|
||||
}
|
||||
} else if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
console.log("\x1b[31mDSQL Database Handler No results returned\x1b[0m =>", results);
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = dsqlDbHandler;
|
@ -1,82 +0,0 @@
|
||||
const decrypt = require("../../functions/decrypt");
|
||||
const defaultFieldsRegexp = require("./defaultFieldsRegexp");
|
||||
|
||||
/**
|
||||
* Parse Database results
|
||||
* ==============================================================================
|
||||
* @description this function takes a database results array gotten from a DB handler
|
||||
* function, decrypts encrypted fields, and returns an updated array with no encrypted
|
||||
* fields
|
||||
*
|
||||
* @param {object} params - Single object params
|
||||
* @param {{}[]} params.unparsedResults - Array of data objects containing Fields(keys)
|
||||
* and corresponding values of the fields(values)
|
||||
* @param {DSQL_TableSchemaType} params.tableSchema - Table schema
|
||||
* @returns {object[]|null}
|
||||
*/
|
||||
module.exports = function parseDbResults({ unparsedResults, tableSchema, encryptionKey, encryptionSalt }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let parsedResults = [];
|
||||
|
||||
/**
|
||||
* Check if query values array is an array
|
||||
*/
|
||||
if (!unparsedResults || !Array.isArray(unparsedResults) || !unparsedResults[0]) {
|
||||
return unparsedResults;
|
||||
}
|
||||
|
||||
try {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
for (let pr = 0; pr < unparsedResults.length; pr++) {
|
||||
let result = unparsedResults[pr];
|
||||
|
||||
let resultFieldNames = Object.keys(result);
|
||||
|
||||
for (let i = 0; i < resultFieldNames.length; i++) {
|
||||
try {
|
||||
const resultFieldName = resultFieldNames[i];
|
||||
let resultFieldSchema = tableSchema?.fields[i];
|
||||
|
||||
if (resultFieldName?.match(defaultFieldsRegexp)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let value = result[resultFieldName];
|
||||
|
||||
if (typeof value !== "number" && !value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (resultFieldSchema?.encrypted) {
|
||||
if (value?.match(/./)) {
|
||||
result[resultFieldName] = decrypt({ encryptedString: value, encryptionKey, encryptionSalt });
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("ERROR in parseDbResults Function =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
parsedResults.push(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
return parsedResults;
|
||||
} catch (error) {
|
||||
console.log("ERROR in parseDbResults Function =>", error.message);
|
||||
return unparsedResults;
|
||||
}
|
||||
};
|
@ -1,9 +0,0 @@
|
||||
const sanitizeHtmlOptions = {
|
||||
allowedTags: ["b", "i", "em", "strong", "a", "p", "span", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "img"],
|
||||
allowedAttributes: {
|
||||
a: ["href"],
|
||||
img: ["src", "alt", "width", "height", "class", "style"],
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = sanitizeHtmlOptions;
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "datasquirel",
|
||||
"version": "1.1.82",
|
||||
"version": "1.1.83",
|
||||
"description": "Cloud-based SQL data management tool",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
@ -14,7 +14,7 @@ const parseCookies = require("../utils/functions/parseCookies");
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* @typedef {object} FunctionReturn
|
||||
* @typedef {object} AuthenticatedUserObject
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {{
|
||||
* id: number,
|
||||
@ -38,9 +38,11 @@ const parseCookies = require("../utils/functions/parseCookies");
|
||||
*/
|
||||
|
||||
/**
|
||||
* Authenticate User from request
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*
|
||||
* @param {Object} params - Arg
|
||||
* @param {Object} params.request - Http request object
|
||||
* @param {String} params.encryptionKey - Encryption Key
|
||||
@ -48,7 +50,7 @@ const parseCookies = require("../utils/functions/parseCookies");
|
||||
* @param {String} params.level - Optional. "Deep" value indicates an extra layer of security
|
||||
* @param {String} params.database - Database Name
|
||||
*
|
||||
* @returns { FunctionReturn }
|
||||
* @returns { AuthenticatedUserObject }
|
||||
*/
|
||||
function userAuth({ request, encryptionKey, encryptionSalt, level, database }) {
|
||||
try {
|
||||
|
@ -50,11 +50,6 @@ function sanitizeSql(input, spaces) {
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
// if (input?.toString()?.match(/\'|\"/)) {
|
||||
// console.log("TEXT containing commas =>", input);
|
||||
// return "";
|
||||
// }
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
@ -19,8 +19,7 @@ const https = require("https");
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* Make a get request to Datasquirel API
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
|
@ -1,7 +1,5 @@
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
|
||||
@ -20,7 +18,7 @@ const https = require("https");
|
||||
|
||||
/**
|
||||
* @typedef {object} PostDataPayload
|
||||
* @property {string} action - "insert" | "update" | "delete"
|
||||
* @property {"insert" | "update" | "delete"} action - The target action to take
|
||||
* @property {string} table - Table name(slug) eg "blog_posts"
|
||||
* @property {string} identifierColumnName - Table identifier field name => eg. "id" OR "email"
|
||||
* @property {string} identifierValue - Corresponding value of the selected field name => This
|
||||
@ -35,8 +33,7 @@ const https = require("https");
|
||||
*/
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* Make a post request to Datasquirel API
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
|
Loading…
Reference in New Issue
Block a user