This commit is contained in:
Benjamin Toby
2023-09-21 15:00:04 +01:00
parent 70ee0a2c0a
commit 44b013147e
77 changed files with 8511 additions and 8495 deletions
+116 -116
View File
@@ -1,116 +1,116 @@
#! /usr/bin/env node
// @ts-check
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
require("dotenv").config({
path: path.resolve(process.cwd(), ".env"),
});
const datasquirel = require("../index");
const createDbFromSchema = require("./engine/createDbFromSchema");
const colors = require("../console-colors");
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
console.log(".env file not found");
process.exit();
}
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, DSQL_ENCRYPTION_KEY, DSQL_ENCRYPTION_SALT } = process.env;
if (!DSQL_HOST?.match(/./)) {
console.log("DSQL_HOST is required in your `.env` file");
process.exit();
}
if (!DSQL_USER?.match(/./)) {
console.log("DSQL_USER is required in your `.env` file");
process.exit();
}
if (!DSQL_PASS?.match(/./)) {
console.log("DSQL_PASS is required in your `.env` file");
process.exit();
}
const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json");
async function run() {
let schemaData;
if (DSQL_KEY && DSQL_REF_DB_NAME?.match(/./)) {
const dbSchemaDataResponse = await datasquirel.getSchema({
key: DSQL_KEY,
database: DSQL_REF_DB_NAME || undefined,
});
if (!dbSchemaDataResponse.payload || Array.isArray(dbSchemaDataResponse.payload)) {
console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
console.log(dbSchemaDataResponse);
process.exit();
}
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
if (DSQL_DB_NAME) fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
schemaData = [fetchedDbSchemaObject];
} else if (DSQL_KEY) {
const dbSchemaDataResponse = await datasquirel.getSchema({
key: DSQL_KEY,
database: DSQL_REF_DB_NAME || undefined,
});
if (!dbSchemaDataResponse.payload || !Array.isArray(dbSchemaDataResponse.payload)) {
console.log("DSQL_KEY => Error in fetching DB schema");
console.log(dbSchemaDataResponse);
process.exit();
}
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
// fetchedDbSchemaObject.forEach((db, index) => {
// db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
// });
schemaData = fetchedDbSchemaObject;
} else if (fs.existsSync(dbSchemaLocalFilePath)) {
schemaData = [JSON.parse(fs.readFileSync(dbSchemaLocalFilePath, "utf8"))];
} else {
console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
process.exit();
}
if (!schemaData) {
console.log("No schema found");
process.exit();
}
if (DSQL_FULL_SYNC?.match(/true/i)) {
fs.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
}
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Now generating and mapping databases ...`);
// deepcode ignore reDOS: <please specify a reason of ignoring this>
await createDbFromSchema(schemaData);
console.log(` - ${colors.FgGreen}Success:${colors.Reset} Databases created Successfully!`);
}
// let timeout;
let interval;
if (fs.existsSync(dbSchemaLocalFilePath) && !DSQL_KEY?.match(/....../)) {
fs.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Syncing Databases Locally ...`);
run();
});
} else if (DSQL_KEY?.match(/....../)) {
interval = setInterval(() => {
console.log(` - ${colors.FgMagenta}Info:${colors.Reset} Syncing Databases from the cloud ...`);
run();
}, 20000);
}
run();
#! /usr/bin/env node
// @ts-check
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
require("dotenv").config({
path: path.resolve(process.cwd(), ".env"),
});
const datasquirel = require("../index");
const createDbFromSchema = require("./engine/createDbFromSchema");
const colors = require("../console-colors");
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
console.log(".env file not found");
process.exit();
}
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, DSQL_ENCRYPTION_KEY, DSQL_ENCRYPTION_SALT } = process.env;
if (!DSQL_HOST?.match(/./)) {
console.log("DSQL_HOST is required in your `.env` file");
process.exit();
}
if (!DSQL_USER?.match(/./)) {
console.log("DSQL_USER is required in your `.env` file");
process.exit();
}
if (!DSQL_PASS?.match(/./)) {
console.log("DSQL_PASS is required in your `.env` file");
process.exit();
}
const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json");
async function run() {
let schemaData;
if (DSQL_KEY && DSQL_REF_DB_NAME?.match(/./)) {
const dbSchemaDataResponse = await datasquirel.getSchema({
key: DSQL_KEY,
database: DSQL_REF_DB_NAME || undefined,
});
if (!dbSchemaDataResponse.payload || Array.isArray(dbSchemaDataResponse.payload)) {
console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
console.log(dbSchemaDataResponse);
process.exit();
}
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
if (DSQL_DB_NAME) fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
schemaData = [fetchedDbSchemaObject];
} else if (DSQL_KEY) {
const dbSchemaDataResponse = await datasquirel.getSchema({
key: DSQL_KEY,
database: DSQL_REF_DB_NAME || undefined,
});
if (!dbSchemaDataResponse.payload || !Array.isArray(dbSchemaDataResponse.payload)) {
console.log("DSQL_KEY => Error in fetching DB schema");
console.log(dbSchemaDataResponse);
process.exit();
}
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
// fetchedDbSchemaObject.forEach((db, index) => {
// db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
// });
schemaData = fetchedDbSchemaObject;
} else if (fs.existsSync(dbSchemaLocalFilePath)) {
schemaData = [JSON.parse(fs.readFileSync(dbSchemaLocalFilePath, "utf8"))];
} else {
console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
process.exit();
}
if (!schemaData) {
console.log("No schema found");
process.exit();
}
if (DSQL_FULL_SYNC?.match(/true/i)) {
fs.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
}
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Now generating and mapping databases ...`);
// deepcode ignore reDOS: <please specify a reason of ignoring this>
await createDbFromSchema(schemaData);
console.log(` - ${colors.FgGreen}Success:${colors.Reset} Databases created Successfully!`);
}
// let timeout;
let interval;
if (fs.existsSync(dbSchemaLocalFilePath) && !DSQL_KEY?.match(/....../)) {
fs.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Syncing Databases Locally ...`);
run();
});
} else if (DSQL_KEY?.match(/....../)) {
interval = setInterval(() => {
console.log(` - ${colors.FgMagenta}Info:${colors.Reset} Syncing Databases from the cloud ...`);
run();
}, 20000);
}
run();
+53 -53
View File
@@ -1,53 +1,53 @@
#! /usr/bin/env node
// @ts-check
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
require("dotenv").config({
path: path.resolve(process.cwd(), ".env"),
});
const mysqlPath = process.platform?.match(/win/i) ? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'" : "mysql";
const mysqlDumpPath = process.platform?.match(/win/i) ? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" + "'" : "mysqldump";
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, DSQL_ENCRYPTION_KEY, DSQL_ENCRYPTION_SALT } = process.env;
const dbName = DSQL_DB_NAME || "";
const dumpFilePathArg = process.argv.indexOf("--file");
if (dumpFilePathArg < 0) {
console.log("Please provide a dump file path using `--file` argument");
process.exit();
}
const dumpFilePath = process.argv[dumpFilePathArg + 1];
if (!dbName?.match(/./)) {
console.log("DSQL_DB_NAME is required in your `.env` file");
process.exit();
}
if (!DSQL_USER?.match(/./) || !DSQL_PASS?.match(/./)) {
console.log("DSQL_USER and DSQL_PASS are required in your `.env` file");
process.exit();
}
try {
let execSyncOptions = {
cwd: process.cwd(),
};
if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
const dump = execSync(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbName} < ${dumpFilePath}`, execSyncOptions);
console.log("Dumped successfully", dump.toString());
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Dump Error: ", error.message);
}
#! /usr/bin/env node
// @ts-check
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
require("dotenv").config({
path: path.resolve(process.cwd(), ".env"),
});
const mysqlPath = process.platform?.match(/win/i) ? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'" : "mysql";
const mysqlDumpPath = process.platform?.match(/win/i) ? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" + "'" : "mysqldump";
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, DSQL_ENCRYPTION_KEY, DSQL_ENCRYPTION_SALT } = process.env;
const dbName = DSQL_DB_NAME || "";
const dumpFilePathArg = process.argv.indexOf("--file");
if (dumpFilePathArg < 0) {
console.log("Please provide a dump file path using `--file` argument");
process.exit();
}
const dumpFilePath = process.argv[dumpFilePathArg + 1];
if (!dbName?.match(/./)) {
console.log("DSQL_DB_NAME is required in your `.env` file");
process.exit();
}
if (!DSQL_USER?.match(/./) || !DSQL_PASS?.match(/./)) {
console.log("DSQL_USER and DSQL_PASS are required in your `.env` file");
process.exit();
}
try {
let execSyncOptions = {
cwd: process.cwd(),
};
if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
const dump = execSync(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbName} < ${dumpFilePath}`, execSyncOptions);
console.log("Dumped successfully", dump.toString());
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Dump Error: ", error.message);
}
+77 -77
View File
@@ -1,77 +1,77 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const updateApiSchemaFromLocalDb = require("../query/update-api-schema-from-local-db");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Add `users` table to user database
* ==============================================================================
*
* @param {object} params - Single object passed
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Database Schema Object
*
* @returns {Promise<*>} new user auth object payload
*/
module.exports = async function addUsersTableToDb({ dbSchema }) {
/**
* Initialize
*
* @description Initialize
*/
const database = process.env.DSQL_DB_NAME || "";
/** @type {import("../../types/database-schema.td").DSQL_TableSchemaType} */
const userPreset = require("./data/presets/users.json");
try {
/**
* Fetch user
*
* @description Fetch user from db
*/
const userSchemaMainFilePath = path.resolve(process.cwd(), "dsql.schema.json");
let targetDatabase = dbSchema;
let existingTableIndex = targetDatabase.tables.findIndex((table, index) => {
if (table.tableName === "users") {
existingTableIndex = index;
return true;
}
});
if (existingTableIndex >= 0) {
targetDatabase.tables[existingTableIndex] = userPreset;
} else {
targetDatabase.tables.push(userPreset);
}
fs.writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(dbSchema, null, 4), "utf8");
////////////////////////////////////////
await updateApiSchemaFromLocalDb();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log(error.message);
}
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const updateApiSchemaFromLocalDb = require("../query/update-api-schema-from-local-db");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Add `users` table to user database
* ==============================================================================
*
* @param {object} params - Single object passed
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Database Schema Object
*
* @returns {Promise<*>} new user auth object payload
*/
module.exports = async function addUsersTableToDb({ dbSchema }) {
/**
* Initialize
*
* @description Initialize
*/
const database = process.env.DSQL_DB_NAME || "";
/** @type {import("../../types/database-schema.td").DSQL_TableSchemaType} */
const userPreset = require("./data/presets/users.json");
try {
/**
* Fetch user
*
* @description Fetch user from db
*/
const userSchemaMainFilePath = path.resolve(process.cwd(), "dsql.schema.json");
let targetDatabase = dbSchema;
let existingTableIndex = targetDatabase.tables.findIndex((table, index) => {
if (table.tableName === "users") {
existingTableIndex = index;
return true;
}
});
if (existingTableIndex >= 0) {
targetDatabase.tables[existingTableIndex] = userPreset;
} else {
targetDatabase.tables.push(userPreset);
}
fs.writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(dbSchema, null, 4), "utf8");
////////////////////////////////////////
await updateApiSchemaFromLocalDb();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log(error.message);
}
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
File diff suppressed because it is too large Load Diff
+73 -73
View File
@@ -1,73 +1,73 @@
[
{
"title": "VARCHAR",
"name": "VARCHAR",
"value": "0-255",
"argument": true,
"description": "Varchar is simply letters and numbers within the range 0 - 255",
"maxValue": 255
},
{
"title": "TINYINT",
"name": "TINYINT",
"value": "0-100",
"description": "TINYINT means Integers: 0 to 100",
"maxValue": 127
},
{
"title": "SMALLINT",
"name": "SMALLINT",
"value": "0-255",
"description": "SMALLINT means Integers: 0 to 240933",
"maxValue": 32767
},
{
"title": "MEDIUMINT",
"name": "MEDIUMINT",
"value": "0-255",
"description": "MEDIUMINT means Integers: 0 to 1245568545560",
"maxValue": 8388607
},
{
"title": "INT",
"name": "INT",
"value": "0-255",
"description": "INT means Integers: 0 to 12560",
"maxValue": 2147483647
},
{
"title": "BIGINT",
"name": "BIGINT",
"value": "0-255",
"description": "BIGINT means Integers: 0 to 1245569056767568545560",
"maxValue": 2e63
},
{
"title": "TINYTEXT",
"name": "TINYTEXT",
"value": "0-255",
"description": "Text with 255 max characters",
"maxValue": 127
},
{
"title": "TEXT",
"name": "TEXT",
"value": "0-100",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "MEDIUMTEXT",
"name": "MEDIUMTEXT",
"value": "0-255",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "LONGTEXT",
"name": "LONGTEXT",
"value": "0-255",
"description": "LONGTEXT is just text with max length 4,294,967,295",
"maxValue": 127
}
]
[
{
"title": "VARCHAR",
"name": "VARCHAR",
"value": "0-255",
"argument": true,
"description": "Varchar is simply letters and numbers within the range 0 - 255",
"maxValue": 255
},
{
"title": "TINYINT",
"name": "TINYINT",
"value": "0-100",
"description": "TINYINT means Integers: 0 to 100",
"maxValue": 127
},
{
"title": "SMALLINT",
"name": "SMALLINT",
"value": "0-255",
"description": "SMALLINT means Integers: 0 to 240933",
"maxValue": 32767
},
{
"title": "MEDIUMINT",
"name": "MEDIUMINT",
"value": "0-255",
"description": "MEDIUMINT means Integers: 0 to 1245568545560",
"maxValue": 8388607
},
{
"title": "INT",
"name": "INT",
"value": "0-255",
"description": "INT means Integers: 0 to 12560",
"maxValue": 2147483647
},
{
"title": "BIGINT",
"name": "BIGINT",
"value": "0-255",
"description": "BIGINT means Integers: 0 to 1245569056767568545560",
"maxValue": 2e63
},
{
"title": "TINYTEXT",
"name": "TINYTEXT",
"value": "0-255",
"description": "Text with 255 max characters",
"maxValue": 127
},
{
"title": "TEXT",
"name": "TEXT",
"value": "0-100",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "MEDIUMTEXT",
"name": "MEDIUMTEXT",
"value": "0-255",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "LONGTEXT",
"name": "LONGTEXT",
"value": "0-255",
"description": "LONGTEXT is just text with max length 4,294,967,295",
"maxValue": 127
}
]
+39 -39
View File
@@ -1,39 +1,39 @@
[
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
}
]
[
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
}
]
+17 -17
View File
@@ -1,17 +1,17 @@
{
"fieldName": "string",
"dataType": "BIGINT",
"nullValue": true,
"primaryKey": true,
"autoIncrement": true,
"defaultValue": "CURRENT_TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP",
"notNullValue": true,
"foreignKey": {
"foreignKeyName": "Name",
"destinationTableName": "Table Name",
"destinationTableColumnName": "Column Name",
"cascadeDelete": true,
"cascadeUpdate": true
}
}
{
"fieldName": "string",
"dataType": "BIGINT",
"nullValue": true,
"primaryKey": true,
"autoIncrement": true,
"defaultValue": "CURRENT_TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP",
"notNullValue": true,
"foreignKey": {
"foreignKeyName": "Name",
"destinationTableName": "Table Name",
"destinationTableColumnName": "Column Name",
"cascadeDelete": true,
"cascadeUpdate": true
}
}
+132 -132
View File
@@ -1,132 +1,132 @@
{
"tableName": "users",
"tableFullName": "Users",
"fields": [
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "first_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "last_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "email",
"dataType": "VARCHAR(200)",
"notNullValue": true
},
{
"fieldName": "phone",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "user_type",
"dataType": "VARCHAR(20)",
"defaultValue": "default"
},
{
"fieldName": "username",
"dataType": "VARCHAR(100)",
"nullValue": true
},
{
"fieldName": "password",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "image",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user_images/user-preset.png"
},
{
"fieldName": "image_thumbnail",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user_images/user-preset-thumbnail.png"
},
{
"fieldName": "address",
"dataType": "VARCHAR(255)"
},
{
"fieldName": "city",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "state",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "country",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "zip_code",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "social_login",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "social_platform",
"dataType": "VARCHAR(50)",
"nullValue": true
},
{
"fieldName": "social_id",
"dataType": "VARCHAR(250)",
"nullValue": true
},
{
"fieldName": "more_user_data",
"dataType": "BIGINT",
"defaultValue": "0"
},
{
"fieldName": "verification_status",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
}
]
}
{
"tableName": "users",
"tableFullName": "Users",
"fields": [
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "first_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "last_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "email",
"dataType": "VARCHAR(200)",
"notNullValue": true
},
{
"fieldName": "phone",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "user_type",
"dataType": "VARCHAR(20)",
"defaultValue": "default"
},
{
"fieldName": "username",
"dataType": "VARCHAR(100)",
"nullValue": true
},
{
"fieldName": "password",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "image",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user_images/user-preset.png"
},
{
"fieldName": "image_thumbnail",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user_images/user-preset-thumbnail.png"
},
{
"fieldName": "address",
"dataType": "VARCHAR(255)"
},
{
"fieldName": "city",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "state",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "country",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "zip_code",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "social_login",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "social_platform",
"dataType": "VARCHAR(50)",
"nullValue": true
},
{
"fieldName": "social_id",
"dataType": "VARCHAR(250)",
"nullValue": true
},
{
"fieldName": "more_user_data",
"dataType": "BIGINT",
"defaultValue": "0"
},
{
"fieldName": "verification_status",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
}
]
}
+54 -54
View File
@@ -1,54 +1,54 @@
// @ts-check
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
function camelJoinedtoCamelSpace(text) {
if (!text?.match(/./)) {
return "";
}
if (text?.match(/ /)) {
return text;
}
if (text) {
let textArray = text.split("");
let capIndexes = [];
for (let i = 0; i < textArray.length; i++) {
const char = textArray[i];
if (i === 0) continue;
if (char.match(/[A-Z]/)) {
capIndexes.push(i);
}
}
let textChunks = [`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`];
for (let j = 0; j < capIndexes.length; j++) {
const capIndex = capIndexes[j];
if (capIndex === 0) continue;
const startIndex = capIndex + 1;
const endIndex = capIndexes[j + 1];
textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`);
}
return textChunks.join(" ");
} else {
return null;
}
}
module.exports = camelJoinedtoCamelSpace;
// @ts-check
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
function camelJoinedtoCamelSpace(text) {
if (!text?.match(/./)) {
return "";
}
if (text?.match(/ /)) {
return text;
}
if (text) {
let textArray = text.split("");
let capIndexes = [];
for (let i = 0; i < textArray.length; i++) {
const char = textArray[i];
if (i === 0) continue;
if (char.match(/[A-Z]/)) {
capIndexes.push(i);
}
}
let textChunks = [`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`];
for (let j = 0; j < capIndexes.length; j++) {
const capIndex = capIndexes[j];
if (capIndex === 0) continue;
const startIndex = capIndex + 1;
const endIndex = capIndexes[j + 1];
textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`);
}
return textChunks.join(" ");
} else {
return null;
}
}
module.exports = camelJoinedtoCamelSpace;
+112 -112
View File
@@ -1,112 +1,112 @@
// @ts-check
const generateColumnDescription = require("./generateColumnDescription");
const supplementTable = require("./supplementTable");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
module.exports = async function createTable({ dbFullName, tableName, tableInfoArray, varDatabaseDbHandler, dbSchema }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
/**
* Grab Schema
*
* @description Grab Schema
*/
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
////////////////////////////////////////
let primaryKeySet = false;
let foreignKeys = [];
////////////////////////////////////////
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField } = column;
if (foreignKey) {
foreignKeys.push({
fieldName: fieldName,
...foreignKey,
});
}
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({ columnData: column, primaryKeySet: primaryKeySet });
primaryKeySet = newPrimaryKeySet;
////////////////////////////////////////
if (fieldName?.match(/updated_timestamp/i)) {
fieldEntryText += " ON UPDATE CURRENT_TIMESTAMP";
}
////////////////////////////////////////
const comma = (() => {
if (foreignKeys[0]) return ",";
if (i === finalTable.length - 1) return "";
return ",";
})();
createTableQueryArray.push(" " + fieldEntryText + comma);
////////////////////////////////////////
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (foreignKeys[0]) {
foreignKeys.forEach((foreighKey, index, array) => {
const { fieldName, destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName } = foreighKey;
const comma = (() => {
if (index === foreignKeys.length - 1) return "";
return ",";
})();
createTableQueryArray.push(` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`);
});
}
////////////////////////////////////////
createTableQueryArray.push(`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`);
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = await varDatabaseDbHandler({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
// @ts-check
const generateColumnDescription = require("./generateColumnDescription");
const supplementTable = require("./supplementTable");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
module.exports = async function createTable({ dbFullName, tableName, tableInfoArray, varDatabaseDbHandler, dbSchema }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
/**
* Grab Schema
*
* @description Grab Schema
*/
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
////////////////////////////////////////
let primaryKeySet = false;
let foreignKeys = [];
////////////////////////////////////////
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField } = column;
if (foreignKey) {
foreignKeys.push({
fieldName: fieldName,
...foreignKey,
});
}
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({ columnData: column, primaryKeySet: primaryKeySet });
primaryKeySet = newPrimaryKeySet;
////////////////////////////////////////
if (fieldName?.match(/updated_timestamp/i)) {
fieldEntryText += " ON UPDATE CURRENT_TIMESTAMP";
}
////////////////////////////////////////
const comma = (() => {
if (foreignKeys[0]) return ",";
if (i === finalTable.length - 1) return "";
return ",";
})();
createTableQueryArray.push(" " + fieldEntryText + comma);
////////////////////////////////////////
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (foreignKeys[0]) {
foreignKeys.forEach((foreighKey, index, array) => {
const { fieldName, destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName } = foreighKey;
const comma = (() => {
if (index === foreignKeys.length - 1) return "";
return ",";
})();
createTableQueryArray.push(` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`);
});
}
////////////////////////////////////////
createTableQueryArray.push(`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`);
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = await varDatabaseDbHandler({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+173 -157
View File
@@ -1,157 +1,173 @@
/** # MODULE TRACE
======================================================================
* Detected 8 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [noDatabaseDbHandler.js](d:\GitHub\dsql\engine\engine\utils\noDatabaseDbHandler.js)
* `require` Statement Found in [varDatabaseDbHandler.js](d:\GitHub\dsql\engine\engine\utils\varDatabaseDbHandler.js)
* `require` Statement Found in [addDbEntry.js](d:\GitHub\dsql\engine\query\utils\addDbEntry.js)
* `require` Statement Found in [deleteDbEntry.js](d:\GitHub\dsql\engine\query\utils\deleteDbEntry.js)
* `require` Statement Found in [runQuery.js](d:\GitHub\dsql\engine\query\utils\runQuery.js)
* `require` Statement Found in [updateDbEntry.js](d:\GitHub\dsql\engine\query\utils\updateDbEntry.js)
* `require` Statement Found in [githubLogin.js](d:\GitHub\dsql\engine\user\social\utils\githubLogin.js)
* `require` Statement Found in [googleLogin.js](d:\GitHub\dsql\engine\user\social\utils\googleLogin.js)
==== MODULE TRACE END ==== */
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const fs = require("fs");
const mysql = require("mysql");
const parseDbResults = require("./parseDbResults");
const connection = mysql.createConnection({
host: process.env.DSQL_HOST,
user: process.env.DSQL_USER,
database: process.env.DSQL_DB_NAME,
password: process.env.DSQL_PASS,
charset: "utf8mb4",
port: process.env.DSQL_PORT?.match(/.../) ? parseInt(process.env.DSQL_PORT) : undefined,
timeout: 5000,
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main DB Handler Function
* ==============================================================================
* @async
* @param {object} params - Single Param object containing params
* @param {string} params.query - Query String
* @param {(string | number)[]} [params.values] - Values
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
* @param {string} [params.database] - Target Database
* @param {string} [params.tableName] - Target Table Name
*
* @returns {Promise<*>}
*/
module.exports = async function dbHandler({ query, values, database, dbSchema, tableName }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let changeDbError;
if (database) {
connection.changeUser({ database: database }, (error) => {
if (error) {
console.log("DB handler error in switching database:", error.message);
changeDbError = error.message;
}
});
}
if (changeDbError) {
return { error: changeDbError };
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
results = await new Promise((resolve, reject) => {
if (values?.[0]) {
connection.query(query, values, (error, results, fields) => {
if (error) {
console.log("DB handler error with values array:", error.message);
console.log("SQL:", error.sql);
console.log("State:", error.sqlState, error.sqlMessage);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
} else {
connection.query(query, (error, results, fields) => {
if (error) {
console.log("DB handler error:", error.message);
console.log("SQL:", error.sql);
console.log("State:", error.sqlState, error.sqlMessage);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("DB handler error:", error.message);
results = null;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
// if (results && dbSchema && tableName) {
// const tableSchema = dbSchema.tables.find((table) => table.tableName === tableName);
// const parsedResults = parseDbResults({
// unparsedResults: results,
// tableSchema: tableSchema,
// });
// return parsedResults;
// } else
if (results) {
return results;
} else {
console.log("DSQL DB handler no results received for Query =>", query);
return null;
}
};
/** # MODULE TRACE
======================================================================
* Detected 8 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [noDatabaseDbHandler.js](d:\GitHub\dsql\engine\engine\utils\noDatabaseDbHandler.js)
* `require` Statement Found in [varDatabaseDbHandler.js](d:\GitHub\dsql\engine\engine\utils\varDatabaseDbHandler.js)
* `require` Statement Found in [addDbEntry.js](d:\GitHub\dsql\engine\query\utils\addDbEntry.js)
* `require` Statement Found in [deleteDbEntry.js](d:\GitHub\dsql\engine\query\utils\deleteDbEntry.js)
* `require` Statement Found in [runQuery.js](d:\GitHub\dsql\engine\query\utils\runQuery.js)
* `require` Statement Found in [updateDbEntry.js](d:\GitHub\dsql\engine\query\utils\updateDbEntry.js)
* `require` Statement Found in [githubLogin.js](d:\GitHub\dsql\engine\user\social\utils\githubLogin.js)
* `require` Statement Found in [googleLogin.js](d:\GitHub\dsql\engine\user\social\utils\googleLogin.js)
==== MODULE TRACE END ==== */
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const fs = require("fs");
const mysql = require("mysql");
const parseDbResults = require("./parseDbResults");
const connection = mysql.createConnection({
host: process.env.DSQL_HOST,
user: process.env.DSQL_USER,
database: process.env.DSQL_DB_NAME,
password: process.env.DSQL_PASS,
charset: "utf8mb4",
port: process.env.DSQL_PORT?.match(/.../)
? parseInt(process.env.DSQL_PORT)
: undefined,
timeout: 5000,
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main DB Handler Function
* ==============================================================================
* @async
* @param {object} params - Single Param object containing params
* @param {string} params.query - Query String
* @param {(string | number)[]} [params.values] - Values
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
* @param {string} [params.database] - Target Database
* @param {string} [params.tableName] - Target Table Name
*
* @returns {Promise<*>}
*/
module.exports = async function dbHandler({
query,
values,
database,
dbSchema,
tableName,
}) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let changeDbError;
console.log(connection.config);
if (database) {
connection.changeUser({ database: database }, (error) => {
if (error) {
console.log(
"DB handler error in switching database:",
error.message
);
changeDbError = error.message;
}
});
}
if (changeDbError) {
return { error: changeDbError };
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
results = await new Promise((resolve, reject) => {
if (values?.[0]) {
connection.query(query, values, (error, results, fields) => {
if (error) {
console.log(
"DB handler error with values array:",
error.message
);
console.log("SQL:", error.sql);
console.log("State:", error.sqlState, error.sqlMessage);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
} else {
connection.query(query, (error, results, fields) => {
if (error) {
console.log("DB handler error:", error.message);
console.log("SQL:", error.sql);
console.log("State:", error.sqlState, error.sqlMessage);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("DB handler error:", error.message);
results = null;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
// if (results && dbSchema && tableName) {
// const tableSchema = dbSchema.tables.find((table) => table.tableName === tableName);
// const parsedResults = parseDbResults({
// unparsedResults: results,
// tableSchema: tableSchema,
// });
// return parsedResults;
// } else
if (results) {
return results;
} else {
console.log("DSQL DB handler no results received for Query =>", query);
return null;
}
};
+13 -13
View File
@@ -1,13 +1,13 @@
/**
* Regular expression to match default fields
*
* @description Regular expression to match default fields
* @type {RegExp}
*/
const defaultFieldsRegexp = /^id$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = defaultFieldsRegexp;
/**
* Regular expression to match default fields
*
* @description Regular expression to match default fields
* @type {RegExp}
*/
const defaultFieldsRegexp = /^id$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = defaultFieldsRegexp;
+16 -16
View File
@@ -1,16 +1,16 @@
// @ts-check
const mysql = require("mysql");
/**
* @param {mysql.Connection} connection - the active MYSQL connection
*/
function endConnection(connection) {
if (connection.state !== "disconnected") {
connection.end((err) => {
console.log(err?.message);
});
}
}
module.exports = endConnection;
// @ts-check
const mysql = require("mysql");
/**
* @param {mysql.Connection} connection - the active MYSQL connection
*/
function endConnection(connection) {
if (connection.state !== "disconnected") {
connection.end((err) => {
console.log(err?.message);
});
}
}
module.exports = endConnection;
@@ -1,68 +1,68 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Generate SQL text for Field
* ==============================================================================
* @param {object} params - Single object params
* @param {import("../../../types/database-schema.td").DSQL_FieldSchemaType} params.columnData - Field object
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
*
* @returns {{fieldEntryText: string, newPrimaryKeySet: boolean}}
*/
module.exports = function generateColumnDescription({ columnData, primaryKeySet }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, notNullValue } = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
if (nullValue) {
fieldEntryText += " DEFAULT NULL";
} else if (defaultValueLiteral) {
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
} else if (defaultValue) {
fieldEntryText += ` DEFAULT '${defaultValue}'`;
} else if (notNullValue) {
fieldEntryText += ` NOT NULL`;
}
////////////////////////////////////////
if (primaryKey && !primaryKeySet) {
fieldEntryText += " PRIMARY KEY";
primaryKeySet = true;
}
////////////////////////////////////////
if (autoIncrement) {
fieldEntryText += " AUTO_INCREMENT";
primaryKeySet = true;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false };
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Generate SQL text for Field
* ==============================================================================
* @param {object} params - Single object params
* @param {import("../../../types/database-schema.td").DSQL_FieldSchemaType} params.columnData - Field object
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
*
* @returns {{fieldEntryText: string, newPrimaryKeySet: boolean}}
*/
module.exports = function generateColumnDescription({ columnData, primaryKeySet }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, notNullValue } = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
if (nullValue) {
fieldEntryText += " DEFAULT NULL";
} else if (defaultValueLiteral) {
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
} else if (defaultValue) {
fieldEntryText += ` DEFAULT '${defaultValue}'`;
} else if (notNullValue) {
fieldEntryText += ` NOT NULL`;
}
////////////////////////////////////////
if (primaryKey && !primaryKeySet) {
fieldEntryText += " PRIMARY KEY";
primaryKeySet = true;
}
////////////////////////////////////////
if (autoIncrement) {
fieldEntryText += " AUTO_INCREMENT";
primaryKeySet = true;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false };
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+89 -89
View File
@@ -1,89 +1,89 @@
// @ts-check
const fs = require("fs");
const dbHandler = require("./dbHandler");
const mysql = require("mysql");
const endConnection = require("./endConnection");
const connection = mysql.createConnection({
host: process.env.DSQL_HOST,
user: process.env.DSQL_USER,
password: process.env.DSQL_PASS,
charset: "utf8mb4",
port: process.env.DSQL_PORT?.match(/.../) ? parseInt(process.env.DSQL_PORT) : undefined,
timeout: 5000,
});
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} params.query - Query String
* @param {string[]} [params.values] - Values
*
* @returns {Promise<object[] | null>}
*/
module.exports = async function noDatabaseDbHandler({ query, values }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
/** ********************* Run Query */
results = await new Promise((resolve, reject) => {
if (values) {
connection.query(query, values, (error, results, fields) => {
if (error) {
console.log("NO-DB handler error:", error.message);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
} else {
connection.query(query, (error, results, fields) => {
if (error) {
console.log("NO-DB handler error:", error.message);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("ERROR in noDatabaseDbHandler =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return results;
} else {
return null;
}
};
// @ts-check
const fs = require("fs");
const dbHandler = require("./dbHandler");
const mysql = require("mysql");
const endConnection = require("./endConnection");
const connection = mysql.createConnection({
host: process.env.DSQL_HOST,
user: process.env.DSQL_USER,
password: process.env.DSQL_PASS,
charset: "utf8mb4",
port: process.env.DSQL_PORT?.match(/.../) ? parseInt(process.env.DSQL_PORT) : undefined,
timeout: 5000,
});
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} params.query - Query String
* @param {string[]} [params.values] - Values
*
* @returns {Promise<object[] | null>}
*/
module.exports = async function noDatabaseDbHandler({ query, values }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
/** ********************* Run Query */
results = await new Promise((resolve, reject) => {
if (values) {
connection.query(query, values, (error, results, fields) => {
if (error) {
console.log("NO-DB handler error:", error.message);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
} else {
connection.query(query, (error, results, fields) => {
if (error) {
console.log("NO-DB handler error:", error.message);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("ERROR in noDatabaseDbHandler =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return results;
} else {
return null;
}
};
+76 -76
View File
@@ -1,76 +1,76 @@
// @ts-check
const decrypt = require("../../../functions/decrypt");
// @ts-ignore
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 {import("../../../types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<object[]|null>}
*/
module.exports = async function parseDbResults({ unparsedResults, tableSchema }) {
/**
* Declare variables
*
* @description Declare "results" variable
* @type {*[]}
*/
let parsedResults = [];
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
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++) {
const resultFieldName = resultFieldNames[i];
let resultFieldSchema = tableSchema?.fields[i];
if (resultFieldName?.match(defaultFieldsRegexp)) {
continue;
}
let value = result[resultFieldName];
if (typeof value !== "number" && !value) {
// parsedResults.push(result);
continue;
}
if (resultFieldSchema?.encrypted && value?.match(/./)) {
result[resultFieldName] = decrypt({ encryptedString: value, encryptionKey, encryptionSalt });
}
}
parsedResults.push(result);
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
return parsedResults;
} catch (/** @type {*} */ error) {
console.log("ERROR in parseDbResults Function =>", error.message);
return unparsedResults;
}
};
// @ts-check
const decrypt = require("../../../functions/decrypt");
// @ts-ignore
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 {import("../../../types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<object[]|null>}
*/
module.exports = async function parseDbResults({ unparsedResults, tableSchema }) {
/**
* Declare variables
*
* @description Declare "results" variable
* @type {*[]}
*/
let parsedResults = [];
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
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++) {
const resultFieldName = resultFieldNames[i];
let resultFieldSchema = tableSchema?.fields[i];
if (resultFieldName?.match(defaultFieldsRegexp)) {
continue;
}
let value = result[resultFieldName];
if (typeof value !== "number" && !value) {
// parsedResults.push(result);
continue;
}
if (resultFieldSchema?.encrypted && value?.match(/./)) {
result[resultFieldName] = decrypt({ encryptedString: value, encryptionKey, encryptionSalt });
}
}
parsedResults.push(result);
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
return parsedResults;
} catch (/** @type {*} */ error) {
console.log("ERROR in parseDbResults Function =>", error.message);
return unparsedResults;
}
};
+16 -16
View File
@@ -1,16 +1,16 @@
// @ts-check
module.exports = function slugToCamelTitle(text) {
if (text) {
let addArray = text.split("-").filter((item) => item !== "");
let camelArray = addArray.map((item) => {
return item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase();
});
let parsedAddress = camelArray.join(" ");
return parsedAddress;
} else {
return null;
}
};
// @ts-check
module.exports = function slugToCamelTitle(text) {
if (text) {
let addArray = text.split("-").filter((item) => item !== "");
let camelArray = addArray.map((item) => {
return item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase();
});
let parsedAddress = camelArray.join(" ");
return parsedAddress;
} else {
return null;
}
};
+48 -48
View File
@@ -1,48 +1,48 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
module.exports = function supplementTable({ tableInfoArray }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
let finalTableArray = tableInfoArray;
const defaultFields = require("../data/defaultFields.json");
////////////////////////////////////////
let primaryKeyExists = finalTableArray.filter((_field) => _field.primaryKey);
////////////////////////////////////////
defaultFields.forEach((field) => {
let fieldExists = finalTableArray.filter((_field) => _field.fieldName === field.fieldName);
if (fieldExists && fieldExists[0]) {
return;
} else if (field.fieldName === "id" && !primaryKeyExists[0]) {
finalTableArray.unshift(field);
} else {
finalTableArray.push(field);
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return finalTableArray;
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
module.exports = function supplementTable({ tableInfoArray }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
let finalTableArray = tableInfoArray;
const defaultFields = require("../data/defaultFields.json");
////////////////////////////////////////
let primaryKeyExists = finalTableArray.filter((_field) => _field.primaryKey);
////////////////////////////////////////
defaultFields.forEach((field) => {
let fieldExists = finalTableArray.filter((_field) => _field.fieldName === field.fieldName);
if (fieldExists && fieldExists[0]) {
return;
} else if (field.fieldName === "id" && !primaryKeyExists[0]) {
finalTableArray.unshift(field);
} else {
finalTableArray.push(field);
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return finalTableArray;
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
File diff suppressed because it is too large Load Diff
+98 -98
View File
@@ -1,98 +1,98 @@
/** # MODULE TRACE
======================================================================
* Detected 9 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [createDbFromSchema.js](d:\GitHub\dsql\engine\engine\createDbFromSchema.js)
* `require` Statement Found in [updateTable.js](d:\GitHub\dsql\engine\engine\utils\updateTable.js)
* `require` Statement Found in [runQuery.js](d:\GitHub\dsql\engine\query\utils\runQuery.js)
* `require` Statement Found in [add-user.js](d:\GitHub\dsql\engine\user\add-user.js)
* `require` Statement Found in [get-user.js](d:\GitHub\dsql\engine\user\get-user.js)
* `require` Statement Found in [login-user.js](d:\GitHub\dsql\engine\user\login-user.js)
* `require` Statement Found in [reauth-user.js](d:\GitHub\dsql\engine\user\reauth-user.js)
* `require` Statement Found in [handleSocialDb.js](d:\GitHub\dsql\engine\user\social\utils\handleSocialDb.js)
* `require` Statement Found in [update-user.js](d:\GitHub\dsql\engine\user\update-user.js)
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
const parseDbResults = require("./parseDbResults");
const dbHandler = require("./dbHandler");
/**
* 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 {import("../../../types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<*>}
*/
module.exports = async function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema }) {
/**
* Create Connection
*
* @description Create Connection
*/
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Declare variables
*
* @description Declare "results" variable
* @type {*}
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (queryString && Array.isArray(queryValuesArray) && queryValuesArray[0]) {
results = await dbHandler({ query: queryString, values: queryValuesArray, database: database });
} else if (queryString && !Array.isArray(queryValuesArray)) {
results = await dbHandler({ query: queryString, database: database });
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (error) {
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results && tableSchema) {
try {
const unparsedResults = results;
// deepcode ignore reDOS: <please specify a reason of ignoring this>
const parsedResults = await parseDbResults({ unparsedResults: unparsedResults, tableSchema: tableSchema });
return parsedResults;
} catch (error) {
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
return null;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else if (results) {
return results;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else {
return null;
}
};
/** # MODULE TRACE
======================================================================
* Detected 9 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [createDbFromSchema.js](d:\GitHub\dsql\engine\engine\createDbFromSchema.js)
* `require` Statement Found in [updateTable.js](d:\GitHub\dsql\engine\engine\utils\updateTable.js)
* `require` Statement Found in [runQuery.js](d:\GitHub\dsql\engine\query\utils\runQuery.js)
* `require` Statement Found in [add-user.js](d:\GitHub\dsql\engine\user\add-user.js)
* `require` Statement Found in [get-user.js](d:\GitHub\dsql\engine\user\get-user.js)
* `require` Statement Found in [login-user.js](d:\GitHub\dsql\engine\user\login-user.js)
* `require` Statement Found in [reauth-user.js](d:\GitHub\dsql\engine\user\reauth-user.js)
* `require` Statement Found in [handleSocialDb.js](d:\GitHub\dsql\engine\user\social\utils\handleSocialDb.js)
* `require` Statement Found in [update-user.js](d:\GitHub\dsql\engine\user\update-user.js)
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
const parseDbResults = require("./parseDbResults");
const dbHandler = require("./dbHandler");
/**
* 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 {import("../../../types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<*>}
*/
module.exports = async function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema }) {
/**
* Create Connection
*
* @description Create Connection
*/
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Declare variables
*
* @description Declare "results" variable
* @type {*}
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (queryString && Array.isArray(queryValuesArray) && queryValuesArray[0]) {
results = await dbHandler({ query: queryString, values: queryValuesArray, database: database });
} else if (queryString && !Array.isArray(queryValuesArray)) {
results = await dbHandler({ query: queryString, database: database });
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (error) {
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results && tableSchema) {
try {
const unparsedResults = results;
// deepcode ignore reDOS: <please specify a reason of ignoring this>
const parsedResults = await parseDbResults({ unparsedResults: unparsedResults, tableSchema: tableSchema });
return parsedResults;
} catch (error) {
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
return null;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else if (results) {
return results;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else {
return null;
}
};
+101 -101
View File
@@ -1,101 +1,101 @@
/** # MODULE TRACE
======================================================================
* No imports found for this Module
==== MODULE TRACE END ==== */
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalGetReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalQueryObject
* @property {string} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalGetReturn> } - Return Object
*/
async function localGet({ options, dbSchema }) {
try {
const { query, queryValues } = options;
/** @type {string | undefined | any } */
const tableName = options?.tableName ? options.tableName : undefined;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query == "string" && (query.match(/^alter|^delete|information_schema|databases|^create/i) || !query.match(/^select/i))) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
let results;
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
queryValuesArray: queryValues,
dbSchema,
tableName,
});
if (error) throw error;
if (!result) throw new Error("No Result received for query => " + query);
if (result?.error) throw new Error(result.error);
results = result;
return { success: true, payload: results };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return { success: false, msg: "Something went wrong!" };
////////////////////////////////////////
}
}
module.exports = localGet;
/** # MODULE TRACE
======================================================================
* No imports found for this Module
==== MODULE TRACE END ==== */
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalGetReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalQueryObject
* @property {string} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalGetReturn> } - Return Object
*/
async function localGet({ options, dbSchema }) {
try {
const { query, queryValues } = options;
/** @type {string | undefined | any } */
const tableName = options?.tableName ? options.tableName : undefined;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query == "string" && (query.match(/^alter|^delete|information_schema|databases|^create/i) || !query.match(/^select/i))) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
let results;
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
queryValuesArray: queryValues,
dbSchema,
tableName,
});
if (error) throw error;
if (!result) throw new Error("No Result received for query => " + query);
if (result?.error) throw new Error(result.error);
results = result;
return { success: true, payload: results };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return { success: false, msg: "Something went wrong!" };
////////////////////////////////////////
}
}
module.exports = localGet;
+100 -100
View File
@@ -1,100 +1,100 @@
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalPostQueryObject
* @property {string | import("../../utils/post").PostDataPayload} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalPostQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localPost({ options, dbSchema }) {
try {
/**
* Grab Body
*/
const { query, tableName, queryValues } = options;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
if (typeof query === "object" && query?.action?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
});
if (error) throw error;
return {
success: true,
payload: result,
error: error,
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local post Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localPost;
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalPostQueryObject
* @property {string | import("../../utils/post").PostDataPayload} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalPostQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localPost({ options, dbSchema }) {
try {
/**
* Grab Body
*/
const { query, tableName, queryValues } = options;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
if (typeof query === "object" && query?.action?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
});
if (error) throw error;
return {
success: true,
payload: result,
error: error,
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local post Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localPost;
+143 -143
View File
@@ -1,143 +1,143 @@
// @ts-check
/**
* Imports
*/
const https = require("https");
const path = require("path");
const fs = require("fs");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - The Y Coordinate
* @property {string} [error] - The Y Coordinate
*/
/**
* # Update API Schema From Local DB
*
* @async
*
* @returns { Promise<PostReturn> } - Return Object
*/
async function updateApiSchemaFromLocalDb() {
try {
/**
* Initialize
*/
const dbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
const key = process.env.DSQL_KEY || "";
const dbSchema = JSON.parse(fs.readFileSync(dbSchemaPath, "utf8"));
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
schema: dbSchema,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
} catch (error) {
console.log(error);
console.log(reqPayloadString);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const httpsRequest = https.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key,
},
port: 443,
hostname: "datasquirel.com",
path: `/api/query/update-schema-from-single-database`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
try {
resolve(JSON.parse(str));
} catch (error) {
console.log(error);
console.log("Fetched Payload =>", str);
resolve({
success: false,
payload: null,
error: error,
});
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: null,
error: err.message,
});
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
} catch (/** @type {*} */ error) {
return {
success: false,
payload: null,
error: error.message,
};
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = updateApiSchemaFromLocalDb;
// @ts-check
/**
* Imports
*/
const https = require("https");
const path = require("path");
const fs = require("fs");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - The Y Coordinate
* @property {string} [error] - The Y Coordinate
*/
/**
* # Update API Schema From Local DB
*
* @async
*
* @returns { Promise<PostReturn> } - Return Object
*/
async function updateApiSchemaFromLocalDb() {
try {
/**
* Initialize
*/
const dbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
const key = process.env.DSQL_KEY || "";
const dbSchema = JSON.parse(fs.readFileSync(dbSchemaPath, "utf8"));
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
schema: dbSchema,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
} catch (error) {
console.log(error);
console.log(reqPayloadString);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const httpsRequest = https.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key,
},
port: 443,
hostname: "datasquirel.com",
path: `/api/query/update-schema-from-single-database`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
try {
resolve(JSON.parse(str));
} catch (error) {
console.log(error);
console.log("Fetched Payload =>", str);
resolve({
success: false,
payload: null,
error: error,
});
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: null,
error: err.message,
});
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
} catch (/** @type {*} */ error) {
return {
success: false,
payload: null,
error: error.message,
};
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = updateApiSchemaFromLocalDb;
+162 -162
View File
@@ -1,162 +1,162 @@
// @ts-check
/**
* Imports: Handle imports
*/
const encrypt = require("../../../functions/encrypt");
const dbHandler = require("../../engine/utils/dbHandler");
const updateDb = require("./updateDbEntry");
const updateDbEntry = require("./updateDbEntry");
/**
* Add a db Entry Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* "Read only" or "Full Access"? Defaults to "Read Only"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {*} params.data - Data to add
* @param {import("../../../types/database-schema.td").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
*
* @returns {Promise<*>}
*/
async function addDbEntry({ dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt }) {
/**
* Initialize variables
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Handle function logic
*/
if (duplicateColumnName && typeof duplicateColumnName === "string") {
const duplicateValue = await dbHandler({
database: dbFullName,
query: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
values: [duplicateColumnValue || ""],
});
if (duplicateValue && duplicateValue[0] && !update) {
return null;
} else if (duplicateValue && duplicateValue[0] && update) {
return await updateDbEntry({
dbFullName,
tableName,
data,
tableSchema,
identifierColumnName: duplicateColumnName,
identifierValue: duplicateColumnValue || "",
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 });
console.log("DSQL: Encrypted value =>", value);
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
if (!value?.toString()?.match(pattern)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
insertKeysArray.push("`" + dataKey + "`");
if (typeof value === "object") {
value = JSON.stringify(value);
}
insertValuesArray.push(value);
} catch (/** @type {*} */ 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 dbHandler({
database: dbFullName,
query: query,
values: queryValuesArray,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return newInsert;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = addDbEntry;
// @ts-check
/**
* Imports: Handle imports
*/
const encrypt = require("../../../functions/encrypt");
const dbHandler = require("../../engine/utils/dbHandler");
const updateDb = require("./updateDbEntry");
const updateDbEntry = require("./updateDbEntry");
/**
* Add a db Entry Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* "Read only" or "Full Access"? Defaults to "Read Only"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {*} params.data - Data to add
* @param {import("../../../types/database-schema.td").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
*
* @returns {Promise<*>}
*/
async function addDbEntry({ dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt }) {
/**
* Initialize variables
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Handle function logic
*/
if (duplicateColumnName && typeof duplicateColumnName === "string") {
const duplicateValue = await dbHandler({
database: dbFullName,
query: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
values: [duplicateColumnValue || ""],
});
if (duplicateValue && duplicateValue[0] && !update) {
return null;
} else if (duplicateValue && duplicateValue[0] && update) {
return await updateDbEntry({
dbFullName,
tableName,
data,
tableSchema,
identifierColumnName: duplicateColumnName,
identifierValue: duplicateColumnValue || "",
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 });
console.log("DSQL: Encrypted value =>", value);
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
if (!value?.toString()?.match(pattern)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
insertKeysArray.push("`" + dataKey + "`");
if (typeof value === "object") {
value = JSON.stringify(value);
}
insertValuesArray.push(value);
} catch (/** @type {*} */ 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 dbHandler({
database: dbFullName,
query: query,
values: queryValuesArray,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return newInsert;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = addDbEntry;
+76 -76
View File
@@ -1,76 +1,76 @@
// @ts-check
const dbHandler = require("../../engine/utils/dbHandler");
/**
* Imports: Handle imports
*/
/**
* Delete DB Entry Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* @param {string} [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 {import("../../../types/database-schema.td").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
*
* @returns {Promise<object|null>}
*/
async function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue }) {
try {
/**
* Check if data is valid
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Execution
*
* @description
*/
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
const deletedEntry = await dbHandler({
query: query,
database: dbFullName,
values: [identifierValue],
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return deletedEntry;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (error) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return null;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = deleteDbEntry;
// @ts-check
const dbHandler = require("../../engine/utils/dbHandler");
/**
* Imports: Handle imports
*/
/**
* Delete DB Entry Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* @param {string} [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 {import("../../../types/database-schema.td").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
*
* @returns {Promise<object|null>}
*/
async function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue }) {
try {
/**
* Check if data is valid
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Execution
*
* @description
*/
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
const deletedEntry = await dbHandler({
query: query,
database: dbFullName,
values: [identifierValue],
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return deletedEntry;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (error) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return null;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = deleteDbEntry;
+165 -165
View File
@@ -1,165 +1,165 @@
/** # MODULE TRACE
======================================================================
* Detected 4 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [get.js](d:\GitHub\dsql\engine\query\get.js)
* `require` Statement Found in [post.js](d:\GitHub\dsql\engine\query\post.js)
* `require` Statement Found in [add-user.js](d:\GitHub\dsql\engine\user\add-user.js)
* `require` Statement Found in [update-user.js](d:\GitHub\dsql\engine\user\update-user.js)
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
const addDbEntry = require("./addDbEntry");
const updateDbEntry = require("./updateDbEntry");
const deleteDbEntry = require("./deleteDbEntry");
const varDatabaseDbHandler = require("../../engine/utils/varDatabaseDbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================
* @param {object} params - An object containing the function parameters.
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
* @param {*} params.query - Query string or object
* @param {boolean} [params.readOnly] - Is this operation read only?
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
* @param {string[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
* @param {string} [params.tableName] - Table Name
*
* @return {Promise<{result: *, error?: *}>}
*/
async function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
let result, error, tableSchema;
if (dbSchema) {
try {
const table = tableName ? tableName : typeof query == "string" ? null : query ? query?.table : null;
if (!table) throw new Error("No table name provided");
tableSchema = dbSchema.tables.filter((tb) => tb?.tableName === table)[0];
} catch (_err) {}
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
try {
if (typeof query === "string") {
result = await varDatabaseDbHandler({
queryString: query,
queryValuesArray,
database: dbFullName,
tableSchema,
});
} else if (typeof query === "object") {
/**
* Declare variables
*
* @description Declare "results" variable
*/
const { data, action, table, identifierColumnName, identifierValue, update, duplicateColumnName, duplicateColumnValue } = query;
switch (action.toLowerCase()) {
case "insert":
result = await addDbEntry({
dbFullName: dbFullName,
tableName: table,
data: data,
update,
duplicateColumnName,
duplicateColumnValue,
tableSchema,
encryptionKey,
encryptionSalt,
});
if (!result?.insertId) {
error = new Error("Couldn't insert data");
}
break;
case "update":
result = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
data: data,
identifierColumnName,
identifierValue,
tableSchema,
encryptionKey,
encryptionSalt,
});
break;
case "delete":
result = await deleteDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
identifierColumnName,
identifierValue,
tableSchema,
});
break;
default:
console.log("Unhandled Query");
console.log("Query Recieved =>", query);
result = {
result: null,
error: "Unhandled Query",
};
break;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in Running Query =>", error.message);
console.log("Query Recieved =>", query);
result = {
result: null,
error: "Error in running Query => " + error.message,
};
error = error.message;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { result, error };
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
module.exports = runQuery;
/** # MODULE TRACE
======================================================================
* Detected 4 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [get.js](d:\GitHub\dsql\engine\query\get.js)
* `require` Statement Found in [post.js](d:\GitHub\dsql\engine\query\post.js)
* `require` Statement Found in [add-user.js](d:\GitHub\dsql\engine\user\add-user.js)
* `require` Statement Found in [update-user.js](d:\GitHub\dsql\engine\user\update-user.js)
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
const addDbEntry = require("./addDbEntry");
const updateDbEntry = require("./updateDbEntry");
const deleteDbEntry = require("./deleteDbEntry");
const varDatabaseDbHandler = require("../../engine/utils/varDatabaseDbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================
* @param {object} params - An object containing the function parameters.
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
* @param {*} params.query - Query string or object
* @param {boolean} [params.readOnly] - Is this operation read only?
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
* @param {string[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
* @param {string} [params.tableName] - Table Name
*
* @return {Promise<{result: *, error?: *}>}
*/
async function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
let result, error, tableSchema;
if (dbSchema) {
try {
const table = tableName ? tableName : typeof query == "string" ? null : query ? query?.table : null;
if (!table) throw new Error("No table name provided");
tableSchema = dbSchema.tables.filter((tb) => tb?.tableName === table)[0];
} catch (_err) {}
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
try {
if (typeof query === "string") {
result = await varDatabaseDbHandler({
queryString: query,
queryValuesArray,
database: dbFullName,
tableSchema,
});
} else if (typeof query === "object") {
/**
* Declare variables
*
* @description Declare "results" variable
*/
const { data, action, table, identifierColumnName, identifierValue, update, duplicateColumnName, duplicateColumnValue } = query;
switch (action.toLowerCase()) {
case "insert":
result = await addDbEntry({
dbFullName: dbFullName,
tableName: table,
data: data,
update,
duplicateColumnName,
duplicateColumnValue,
tableSchema,
encryptionKey,
encryptionSalt,
});
if (!result?.insertId) {
error = new Error("Couldn't insert data");
}
break;
case "update":
result = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
data: data,
identifierColumnName,
identifierValue,
tableSchema,
encryptionKey,
encryptionSalt,
});
break;
case "delete":
result = await deleteDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
identifierColumnName,
identifierValue,
tableSchema,
});
break;
default:
console.log("Unhandled Query");
console.log("Query Recieved =>", query);
result = {
result: null,
error: "Unhandled Query",
};
break;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in Running Query =>", error.message);
console.log("Query Recieved =>", query);
result = {
result: null,
error: "Error in running Query => " + error.message,
};
error = error.message;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { result, error };
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
module.exports = runQuery;
+149 -149
View File
@@ -1,149 +1,149 @@
// @ts-check
const encrypt = require("../../../functions/encrypt");
const dbHandler = require("../../engine/utils/dbHandler");
/**
* Imports: Handle imports
*/
/**
* 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"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {*} params.data - Data to add
* @param {import("../../../types/database-schema.td").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 {string} params.encryptionKey - Encryption key
* @param {string} params.encryptionSalt - Encryption salt
*
* @returns {Promise<object|null>}
*/
async function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, 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 = [];
/**
* Declare variables
*
* @description Declare "results" variable
*/
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 (typeof value == "undefined") continue;
if (typeof value !== "string" && typeof value !== "number" && !value) continue;
if (targetFieldSchema?.encrypted) {
value = encrypt({ data: value, encryptionKey, encryptionSalt });
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
if (typeof value === "string" && value.match(/^null$/i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
if (!value?.toString()?.match(pattern)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (!value && typeof value == "number" && value != 0) continue;
updateKeyValueArray.push(`\`${dataKey}\`=?`);
updateValues.push(value);
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ 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 dbHandler({
database: dbFullName,
query: query,
values: updateValues,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return updatedEntry;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = updateDbEntry;
// @ts-check
const encrypt = require("../../../functions/encrypt");
const dbHandler = require("../../engine/utils/dbHandler");
/**
* Imports: Handle imports
*/
/**
* 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"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {*} params.data - Data to add
* @param {import("../../../types/database-schema.td").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 {string} params.encryptionKey - Encryption key
* @param {string} params.encryptionSalt - Encryption salt
*
* @returns {Promise<object|null>}
*/
async function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, 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 = [];
/**
* Declare variables
*
* @description Declare "results" variable
*/
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 (typeof value == "undefined") continue;
if (typeof value !== "string" && typeof value !== "number" && !value) continue;
if (targetFieldSchema?.encrypted) {
value = encrypt({ data: value, encryptionKey, encryptionSalt });
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
if (typeof value === "string" && value.match(/^null$/i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
if (!value?.toString()?.match(pattern)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (!value && typeof value == "number" && value != 0) continue;
updateKeyValueArray.push(`\`${dataKey}\`=?`);
updateValues.push(value);
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ 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 dbHandler({
database: dbFullName,
query: query,
values: updateValues,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return updatedEntry;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = updateDbEntry;
+153 -153
View File
@@ -1,153 +1,153 @@
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const addUsersTableToDb = require("../engine/addUsersTableToDb");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
const addDbEntry = require("../query/utils/addDbEntry");
const runQuery = require("../query/utils/runQuery");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {import("../../users/add-user").UserDataPayload} params.payload - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localAddUser({ payload, dbSchema }) {
try {
/**
* Initialize Variables
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Hash Password
*
* @description Hash Password
*/
if (!payload?.password) {
return { success: false, payload: `Password is required to create an account` };
}
const hashedPassword = hashPassword({
password: payload.password,
encryptionKey,
});
payload.password = hashedPassword;
let fields = await varDatabaseDbHandler({
queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
if (!fields) {
const newTable = await addUsersTableToDb({ dbSchema });
console.log(newTable);
fields = await varDatabaseDbHandler({
queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
}
if (!fields) {
return {
success: false,
payload: "Could not create users table",
};
}
const fieldsTitles = fields.map((/** @type {*} */ fieldObject) => fieldObject.Field);
let invalidField = null;
for (let i = 0; i < Object.keys(payload).length; i++) {
const key = Object.keys(payload)[i];
if (!fieldsTitles.includes(key)) {
invalidField = key;
break;
}
}
if (invalidField) {
return { success: false, payload: `${invalidField} is not a valid field!` };
}
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
const existingUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ?${payload.username ? "OR username = ?" : ""}}`,
queryValuesArray: payload.username ? [payload.email, payload.username] : [payload.email],
database: dbFullName,
tableSchema: tableSchema,
});
if (existingUser && existingUser[0]) {
return {
success: false,
payload: "User Already Exists",
};
}
const addUser = await addDbEntry({
dbFullName: dbFullName,
tableName: "users",
data: {
...payload,
image: "/images/user_images/user-preset.png",
image_thumbnail: "/images/user_images/user-preset-thumbnail.png",
},
encryptionKey,
encryptionSalt,
tableSchema,
});
if (addUser?.insertId) {
const newlyAddedUser = await varDatabaseDbHandler({
queryString: `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`,
database: dbFullName,
});
return {
success: true,
payload: newlyAddedUser?.[0],
};
} else {
return {
success: false,
payload: "Could not create user",
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local add-user Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localAddUser;
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const addUsersTableToDb = require("../engine/addUsersTableToDb");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
const addDbEntry = require("../query/utils/addDbEntry");
const runQuery = require("../query/utils/runQuery");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {import("../../users/add-user").UserDataPayload} params.payload - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localAddUser({ payload, dbSchema }) {
try {
/**
* Initialize Variables
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Hash Password
*
* @description Hash Password
*/
if (!payload?.password) {
return { success: false, payload: `Password is required to create an account` };
}
const hashedPassword = hashPassword({
password: payload.password,
encryptionKey,
});
payload.password = hashedPassword;
let fields = await varDatabaseDbHandler({
queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
if (!fields) {
const newTable = await addUsersTableToDb({ dbSchema });
console.log(newTable);
fields = await varDatabaseDbHandler({
queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
}
if (!fields) {
return {
success: false,
payload: "Could not create users table",
};
}
const fieldsTitles = fields.map((/** @type {*} */ fieldObject) => fieldObject.Field);
let invalidField = null;
for (let i = 0; i < Object.keys(payload).length; i++) {
const key = Object.keys(payload)[i];
if (!fieldsTitles.includes(key)) {
invalidField = key;
break;
}
}
if (invalidField) {
return { success: false, payload: `${invalidField} is not a valid field!` };
}
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
const existingUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ?${payload.username ? "OR username = ?" : ""}}`,
queryValuesArray: payload.username ? [payload.email, payload.username] : [payload.email],
database: dbFullName,
tableSchema: tableSchema,
});
if (existingUser && existingUser[0]) {
return {
success: false,
payload: "User Already Exists",
};
}
const addUser = await addDbEntry({
dbFullName: dbFullName,
tableName: "users",
data: {
...payload,
image: "/images/user_images/user-preset.png",
image_thumbnail: "/images/user_images/user-preset-thumbnail.png",
},
encryptionKey,
encryptionSalt,
tableSchema,
});
if (addUser?.insertId) {
const newlyAddedUser = await varDatabaseDbHandler({
queryString: `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`,
database: dbFullName,
});
return {
success: true,
payload: newlyAddedUser?.[0],
};
} else {
return {
success: false,
payload: "Could not create user",
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local add-user Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localAddUser;
+53 -53
View File
@@ -1,53 +1,53 @@
// @ts-check
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {number} param0.userId
* @param {string[]} param0.fields
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
async function getLocalUser({ userId, fields, dbSchema }) {
/**
* GRAB user
*
* @description GRAB user
*/
const sanitizedFields = fields.map((fld) => fld.replace(/[^a-z\_]/g, ""));
const query = `SELECT ${sanitizedFields.join(",")} FROM users WHERE id = ?`;
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
let foundUser = await varDatabaseDbHandler({
queryString: query,
queryValuesArray: [userId.toString()],
database: process.env.DSQL_DB_NAME || "",
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "User not found!",
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
payload: foundUser[0],
};
}
module.exports = getLocalUser;
// @ts-check
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {number} param0.userId
* @param {string[]} param0.fields
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
async function getLocalUser({ userId, fields, dbSchema }) {
/**
* GRAB user
*
* @description GRAB user
*/
const sanitizedFields = fields.map((fld) => fld.replace(/[^a-z\_]/g, ""));
const query = `SELECT ${sanitizedFields.join(",")} FROM users WHERE id = ?`;
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
let foundUser = await varDatabaseDbHandler({
queryString: query,
queryValuesArray: [userId.toString()],
database: process.env.DSQL_DB_NAME || "",
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "User not found!",
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
payload: foundUser[0],
};
}
module.exports = getLocalUser;
+152 -152
View File
@@ -1,152 +1,152 @@
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {{
* email?: string,
* username?: string,
* password: string,
* }} param0.payload
* @param {string[]} [param0.additionalFields]
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
async function loginLocalUser({ payload, additionalFields, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
const { email, username, password } = payload;
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Check input validity
*
* @description Check input validity
*/
if (email?.match(/ /) || username?.match(/ /) || password?.match(/ /)) {
return {
success: false,
msg: "Invalid Email/Password format",
};
}
/**
* Password hash
*
* @description Password hash
*/
let hashedPassword = hashPassword({
password: password,
encryptionKey: encryptionKey,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
let foundUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
queryValuesArray: [email || "", username || ""],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
let isPasswordCorrect = false;
if (foundUser && foundUser[0]) {
isPasswordCorrect = hashedPassword === foundUser[0].password;
}
let socialUserValid = false;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!isPasswordCorrect && !socialUserValid) {
return {
success: false,
msg: "Wrong password, no social login validity",
payload: null,
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
let userPayload = {
id: foundUser[0].id,
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
phone: foundUser[0].phone,
social_id: foundUser[0].social_id,
image: foundUser[0].image,
image_thumbnail: foundUser[0].image_thumbnail,
verification_status: foundUser[0].verification_status,
social_login: foundUser[0].social_login,
social_platform: foundUser[0].social_platform,
csrf_k: csrfKey,
more_data: foundUser[0].more_user_data,
logged_in_status: true,
date: Date.now(),
};
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
additionalFields.forEach((key) => {
// @ts-ignore
userPayload[key] = foundUser?.[0][key];
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Login Successful",
payload: userPayload,
userId: "0",
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Login Failed",
};
}
}
module.exports = loginLocalUser;
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {{
* email?: string,
* username?: string,
* password: string,
* }} param0.payload
* @param {string[]} [param0.additionalFields]
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
async function loginLocalUser({ payload, additionalFields, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
const { email, username, password } = payload;
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Check input validity
*
* @description Check input validity
*/
if (email?.match(/ /) || username?.match(/ /) || password?.match(/ /)) {
return {
success: false,
msg: "Invalid Email/Password format",
};
}
/**
* Password hash
*
* @description Password hash
*/
let hashedPassword = hashPassword({
password: password,
encryptionKey: encryptionKey,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
let foundUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
queryValuesArray: [email || "", username || ""],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
let isPasswordCorrect = false;
if (foundUser && foundUser[0]) {
isPasswordCorrect = hashedPassword === foundUser[0].password;
}
let socialUserValid = false;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!isPasswordCorrect && !socialUserValid) {
return {
success: false,
msg: "Wrong password, no social login validity",
payload: null,
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
let userPayload = {
id: foundUser[0].id,
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
phone: foundUser[0].phone,
social_id: foundUser[0].social_id,
image: foundUser[0].image,
image_thumbnail: foundUser[0].image_thumbnail,
verification_status: foundUser[0].verification_status,
social_login: foundUser[0].social_login,
social_platform: foundUser[0].social_platform,
csrf_k: csrfKey,
more_data: foundUser[0].more_user_data,
logged_in_status: true,
date: Date.now(),
};
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
additionalFields.forEach((key) => {
// @ts-ignore
userPayload[key] = foundUser?.[0][key];
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Login Successful",
payload: userPayload,
userId: "0",
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Login Failed",
};
}
}
module.exports = loginLocalUser;
+106 -106
View File
@@ -1,106 +1,106 @@
// @ts-check
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {*} param0.existingUser
* @param {string[]} [param0.additionalFields]
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
async function localReauthUser({ existingUser, additionalFields, dbSchema }) {
try {
/**
* Grab data
*
* @description Grab data
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* GRAB user
*
* @description GRAB user
*/
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
let foundUser =
existingUser?.id && existingUser.id.toString().match(/./)
? await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE id=?`,
queryValuesArray: [existingUser.id],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
})
: null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
let userPayload = {
id: foundUser[0].id,
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
phone: foundUser[0].phone,
social_id: foundUser[0].social_id,
image: foundUser[0].image,
image_thumbnail: foundUser[0].image_thumbnail,
verification_status: foundUser[0].verification_status,
social_login: foundUser[0].social_login,
social_platform: foundUser[0].social_platform,
csrf_k: csrfKey,
more_data: foundUser[0].more_user_data,
logged_in_status: true,
date: Date.now(),
};
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
additionalFields.forEach((key) => {
// @ts-ignore
userPayload[key] = foundUser?.[0][key];
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Login Successful",
payload: userPayload,
userId: "0",
};
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Login Failed",
};
}
}
module.exports = localReauthUser;
// @ts-check
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {*} param0.existingUser
* @param {string[]} [param0.additionalFields]
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
async function localReauthUser({ existingUser, additionalFields, dbSchema }) {
try {
/**
* Grab data
*
* @description Grab data
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* GRAB user
*
* @description GRAB user
*/
const tableSchema = dbSchema?.tables.find((tb) => tb?.tableName === "users");
let foundUser =
existingUser?.id && existingUser.id.toString().match(/./)
? await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE id=?`,
queryValuesArray: [existingUser.id],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
})
: null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
let userPayload = {
id: foundUser[0].id,
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
phone: foundUser[0].phone,
social_id: foundUser[0].social_id,
image: foundUser[0].image,
image_thumbnail: foundUser[0].image_thumbnail,
verification_status: foundUser[0].verification_status,
social_login: foundUser[0].social_login,
social_platform: foundUser[0].social_platform,
csrf_k: csrfKey,
more_data: foundUser[0].more_user_data,
logged_in_status: true,
date: Date.now(),
};
if (additionalFields && Array.isArray(additionalFields) && additionalFields.length > 0) {
additionalFields.forEach((key) => {
// @ts-ignore
userPayload[key] = foundUser?.[0][key];
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Login Successful",
payload: userPayload,
userId: "0",
};
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Login Failed",
};
}
}
module.exports = localReauthUser;
+134 -134
View File
@@ -1,134 +1,134 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const https = require("https");
const encrypt = require("../../../functions/encrypt");
const camelJoinedtoCamelSpace = require("../../engine/utils/camelJoinedtoCamelSpace");
const githubLogin = require("./utils/githubLogin");
const handleSocialDb = require("./utils/handleSocialDb");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {http.ServerResponse} params.res - HTTPS response object
* @param {string} params.code
* @param {string} [params.email]
* @param {string} params.clientId
* @param {string} params.clientSecret
* @param {object} [params.additionalFields]
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema
*/
async function localGithubAuth({ res, code, email, clientId, clientSecret, additionalFields, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
if (!code || !clientId || !clientSecret) {
return {
success: false,
msg: "Missing query params",
};
}
if (typeof code !== "string" || typeof clientId !== "string" || typeof clientSecret !== "string" || typeof database !== "string") {
return {
success: false,
msg: "Wrong Parameters",
};
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
const gitHubUser = await githubLogin({
code: code,
clientId: clientId,
clientSecret: clientSecret,
});
if (!gitHubUser) {
return {
success: false,
msg: "No github user returned",
};
}
const targetDbName = database;
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
const targetName = gitHubUser.name || gitHubUser.login;
const nameArray = targetName?.match(/ /) ? targetName?.split(" ") : targetName?.match(/\-/) ? targetName?.split("-") : [targetName];
const payload = {
email: gitHubUser.email,
first_name: camelJoinedtoCamelSpace(nameArray[0]) || "",
last_name: camelJoinedtoCamelSpace(nameArray[1]) || "",
social_id: socialId,
social_platform: "github",
image: gitHubUser.avatar_url,
image_thumbnail: gitHubUser.avatar_url,
username: "github-user-" + socialId,
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key) => {
// @ts-ignore
payload[key] = additionalFields[key];
});
}
const loggedInGithubUser = await handleSocialDb({
database: targetDbName,
email: gitHubUser.email,
payload: payload,
social_platform: "github",
res: res,
social_id: socialId,
supEmail: email,
additionalFields,
dbSchema: dbSchema,
});
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return { ...loggedInGithubUser, dsqlUserId: "0" };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("localGithubAuth error", error.message);
return { success: false, msg: "Failed!" };
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = localGithubAuth;
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const https = require("https");
const encrypt = require("../../../functions/encrypt");
const camelJoinedtoCamelSpace = require("../../engine/utils/camelJoinedtoCamelSpace");
const githubLogin = require("./utils/githubLogin");
const handleSocialDb = require("./utils/handleSocialDb");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {http.ServerResponse} params.res - HTTPS response object
* @param {string} params.code
* @param {string} [params.email]
* @param {string} params.clientId
* @param {string} params.clientSecret
* @param {object} [params.additionalFields]
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema
*/
async function localGithubAuth({ res, code, email, clientId, clientSecret, additionalFields, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
if (!code || !clientId || !clientSecret) {
return {
success: false,
msg: "Missing query params",
};
}
if (typeof code !== "string" || typeof clientId !== "string" || typeof clientSecret !== "string" || typeof database !== "string") {
return {
success: false,
msg: "Wrong Parameters",
};
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
const gitHubUser = await githubLogin({
code: code,
clientId: clientId,
clientSecret: clientSecret,
});
if (!gitHubUser) {
return {
success: false,
msg: "No github user returned",
};
}
const targetDbName = database;
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
const targetName = gitHubUser.name || gitHubUser.login;
const nameArray = targetName?.match(/ /) ? targetName?.split(" ") : targetName?.match(/\-/) ? targetName?.split("-") : [targetName];
const payload = {
email: gitHubUser.email,
first_name: camelJoinedtoCamelSpace(nameArray[0]) || "",
last_name: camelJoinedtoCamelSpace(nameArray[1]) || "",
social_id: socialId,
social_platform: "github",
image: gitHubUser.avatar_url,
image_thumbnail: gitHubUser.avatar_url,
username: "github-user-" + socialId,
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key) => {
// @ts-ignore
payload[key] = additionalFields[key];
});
}
const loggedInGithubUser = await handleSocialDb({
database: targetDbName,
email: gitHubUser.email,
payload: payload,
social_platform: "github",
res: res,
social_id: socialId,
supEmail: email,
additionalFields,
dbSchema: dbSchema,
});
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return { ...loggedInGithubUser, dsqlUserId: "0" };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("localGithubAuth error", error.message);
return { success: false, msg: "Failed!" };
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = localGithubAuth;
+169 -169
View File
@@ -1,169 +1,169 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const encrypt = require("../../../functions/encrypt");
const decrypt = require("../../../functions/decrypt");
const handleSocialDb = require("./utils/handleSocialDb");
const httpsRequest = require("./utils/httpsRequest");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {object | null} FunctionReturn
* @property {boolean} success - Did the function run successfully?
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
* @property {number} [dsqlUserId] - Dsql User Id
* @property {string} [msg] - Response message
*/
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {string} params.token - Google access token gotten from the client side
* @param {string} params.clientId - Google client id
* @param {http.ServerResponse} params.response - HTTPS response object
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
*
* @returns { Promise<FunctionReturn> }
*/
async function localGoogleAuth({ dbSchema, token, clientId, response, additionalFields }) {
/**
* Send Response
*
* @description Send a boolean response
*/
try {
/**
* Grab User data
*
* @description Grab User data
* @type {{ success: boolean, payload: any, msg: string }}
*/
const payloadResponse = await httpsRequest({
method: "POST",
hostname: "datasquirel.com",
path: "/user/grab-google-user-from-token",
body: {
token: token,
clientId: clientId,
},
headers: {
Authorization: process.env.DSQL_API_KEY,
},
});
const payload = payloadResponse.payload;
if (!payloadResponse.success || !payload) {
console.log("payloadResponse Failed =>", payloadResponse);
return {
success: false,
msg: "User fetch Error",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!database || typeof database != "string" || database?.match(/ /)) {
return {
success: false,
user: undefined,
msg: "Please provide a database slug(database name in lowercase with no spaces)",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
const targetDbName = database;
if (!payload) {
return {
success: false,
msg: "No payload",
};
}
const { given_name, family_name, email, sub, picture, email_verified } = payload;
const payloadObject = {
email: email || "",
first_name: given_name || "",
last_name: family_name || "",
social_id: sub,
social_platform: "google",
image: picture || "",
image_thumbnail: picture || "",
username: `google-user-${sub}`,
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key) => {
// @ts-ignore
payloadObject[key] = additionalFields[key];
});
}
const loggedInGoogleUser = await handleSocialDb({
database: targetDbName,
email: email || "",
payload: payloadObject,
social_platform: "google",
res: response,
social_id: sub,
additionalFields,
dbSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { ...loggedInGoogleUser, dsqlUserId: "0" };
////////////////////////////////////////
} catch (error) {
return {
success: false,
msg: "User fetch Error",
};
////////////////////////////////////////
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = localGoogleAuth;
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const encrypt = require("../../../functions/encrypt");
const decrypt = require("../../../functions/decrypt");
const handleSocialDb = require("./utils/handleSocialDb");
const httpsRequest = require("./utils/httpsRequest");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {object | null} FunctionReturn
* @property {boolean} success - Did the function run successfully?
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
* @property {number} [dsqlUserId] - Dsql User Id
* @property {string} [msg] - Response message
*/
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {string} params.token - Google access token gotten from the client side
* @param {string} params.clientId - Google client id
* @param {http.ServerResponse} params.response - HTTPS response object
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
*
* @returns { Promise<FunctionReturn> }
*/
async function localGoogleAuth({ dbSchema, token, clientId, response, additionalFields }) {
/**
* Send Response
*
* @description Send a boolean response
*/
try {
/**
* Grab User data
*
* @description Grab User data
* @type {{ success: boolean, payload: any, msg: string }}
*/
const payloadResponse = await httpsRequest({
method: "POST",
hostname: "datasquirel.com",
path: "/user/grab-google-user-from-token",
body: {
token: token,
clientId: clientId,
},
headers: {
Authorization: process.env.DSQL_API_KEY,
},
});
const payload = payloadResponse.payload;
if (!payloadResponse.success || !payload) {
console.log("payloadResponse Failed =>", payloadResponse);
return {
success: false,
msg: "User fetch Error",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!database || typeof database != "string" || database?.match(/ /)) {
return {
success: false,
user: undefined,
msg: "Please provide a database slug(database name in lowercase with no spaces)",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
const targetDbName = database;
if (!payload) {
return {
success: false,
msg: "No payload",
};
}
const { given_name, family_name, email, sub, picture, email_verified } = payload;
const payloadObject = {
email: email || "",
first_name: given_name || "",
last_name: family_name || "",
social_id: sub,
social_platform: "google",
image: picture || "",
image_thumbnail: picture || "",
username: `google-user-${sub}`,
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key) => {
// @ts-ignore
payloadObject[key] = additionalFields[key];
});
}
const loggedInGoogleUser = await handleSocialDb({
database: targetDbName,
email: email || "",
payload: payloadObject,
social_platform: "google",
res: response,
social_id: sub,
additionalFields,
dbSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { ...loggedInGoogleUser, dsqlUserId: "0" };
////////////////////////////////////////
} catch (error) {
return {
success: false,
msg: "User fetch Error",
};
////////////////////////////////////////
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = localGoogleAuth;
+164 -164
View File
@@ -1,164 +1,164 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const httpsRequest = require("./httpsRequest");
const dbHandler = require("../../../engine/utils/dbHandler");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
*
* @typedef {object} GithubUserPayload
* @property {string} login - Full name merged eg. "JohnDoe"
* @property {number} id - github user id
* @property {string} node_id - Some other id
* @property {string} avatar_url - profile picture
* @property {string} gravatar_id - some other id
* @property {string} url - Github user URL
* @property {string} html_url - User html URL - whatever that means
* @property {string} followers_url - Followers URL
* @property {string} following_url - Following URL
* @property {string} gists_url - Gists URL
* @property {string} starred_url - Starred URL
* @property {string} subscriptions_url - Subscriptions URL
* @property {string} organizations_url - Organizations URL
* @property {string} repos_url - Repositories URL
* @property {string} received_events_url - Received Events URL
* @property {string} type - Common value => "User"
* @property {boolean} site_admin - Is site admin or not? Boolean
* @property {string} name - More like "username"
* @property {string} company - User company
* @property {string} blog - User blog URL
* @property {string} location - User Location
* @property {string} email - User Email
* @property {string} hireable - Is user hireable
* @property {string} bio - User bio
* @property {string} twitter_username - User twitter username
* @property {number} public_repos - Number of public repositories
* @property {number} public_gists - Number of public gists
* @property {number} followers - Number of followers
* @property {number} following - Number of following
* @property {string} created_at - Date created
* @property {string} updated_at - Date updated
*/
/**
* Login/signup a github user
* ==============================================================================
* @async
*
* @param {Object} params - foundUser if any
* @param {string} params.code - github auth token
* @param {string} params.clientId - github client Id
* @param {string} params.clientSecret - github client Secret
*
* @returns {Promise<GithubUserPayload|null>}
*/
async function githubLogin({ code, clientId, clientSecret }) {
/** @type {GithubUserPayload | null} */
let gitHubUser = null;
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
try {
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}`);
const response = await httpsRequest({
method: "POST",
hostname: "github.com",
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
headers: {
Accept: "application/json",
"User-Agent": "*",
},
});
// `https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`,
// body: JSON.stringify({
// client_id: process.env.GITHUB_ID,
// client_secret: process.env.GITHUB_SECRET,
// code: code,
// }),
const accessTokenObject = JSON.parse(response);
if (!accessTokenObject?.access_token) {
return gitHubUser;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const userDataResponse = await httpsRequest({
method: "GET",
hostname: "api.github.com",
path: "/user",
headers: {
Authorization: `Bearer ${accessTokenObject.access_token}`,
"User-Agent": "*",
},
});
gitHubUser = JSON.parse(userDataResponse);
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
if (!gitHubUser?.email) {
const existingGithubUser = await dbHandler({
query: `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id= ?`,
values: [gitHubUser?.id || ""],
});
if (existingGithubUser && existingGithubUser[0] && gitHubUser) {
gitHubUser.email = existingGithubUser[0].email;
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
console.log("ERROR in githubLogin.js backend function =>", error.message);
// serverError({
// component: "/api/social-login/github-auth/catch-error",
// message: error.message,
// user: user,
// });
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return gitHubUser;
}
module.exports = githubLogin;
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const httpsRequest = require("./httpsRequest");
const dbHandler = require("../../../engine/utils/dbHandler");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
*
* @typedef {object} GithubUserPayload
* @property {string} login - Full name merged eg. "JohnDoe"
* @property {number} id - github user id
* @property {string} node_id - Some other id
* @property {string} avatar_url - profile picture
* @property {string} gravatar_id - some other id
* @property {string} url - Github user URL
* @property {string} html_url - User html URL - whatever that means
* @property {string} followers_url - Followers URL
* @property {string} following_url - Following URL
* @property {string} gists_url - Gists URL
* @property {string} starred_url - Starred URL
* @property {string} subscriptions_url - Subscriptions URL
* @property {string} organizations_url - Organizations URL
* @property {string} repos_url - Repositories URL
* @property {string} received_events_url - Received Events URL
* @property {string} type - Common value => "User"
* @property {boolean} site_admin - Is site admin or not? Boolean
* @property {string} name - More like "username"
* @property {string} company - User company
* @property {string} blog - User blog URL
* @property {string} location - User Location
* @property {string} email - User Email
* @property {string} hireable - Is user hireable
* @property {string} bio - User bio
* @property {string} twitter_username - User twitter username
* @property {number} public_repos - Number of public repositories
* @property {number} public_gists - Number of public gists
* @property {number} followers - Number of followers
* @property {number} following - Number of following
* @property {string} created_at - Date created
* @property {string} updated_at - Date updated
*/
/**
* Login/signup a github user
* ==============================================================================
* @async
*
* @param {Object} params - foundUser if any
* @param {string} params.code - github auth token
* @param {string} params.clientId - github client Id
* @param {string} params.clientSecret - github client Secret
*
* @returns {Promise<GithubUserPayload|null>}
*/
async function githubLogin({ code, clientId, clientSecret }) {
/** @type {GithubUserPayload | null} */
let gitHubUser = null;
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
try {
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}`);
const response = await httpsRequest({
method: "POST",
hostname: "github.com",
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
headers: {
Accept: "application/json",
"User-Agent": "*",
},
});
// `https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`,
// body: JSON.stringify({
// client_id: process.env.GITHUB_ID,
// client_secret: process.env.GITHUB_SECRET,
// code: code,
// }),
const accessTokenObject = JSON.parse(response);
if (!accessTokenObject?.access_token) {
return gitHubUser;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const userDataResponse = await httpsRequest({
method: "GET",
hostname: "api.github.com",
path: "/user",
headers: {
Authorization: `Bearer ${accessTokenObject.access_token}`,
"User-Agent": "*",
},
});
gitHubUser = JSON.parse(userDataResponse);
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
if (!gitHubUser?.email) {
const existingGithubUser = await dbHandler({
query: `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id= ?`,
values: [gitHubUser?.id || ""],
});
if (existingGithubUser && existingGithubUser[0] && gitHubUser) {
gitHubUser.email = existingGithubUser[0].email;
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
console.log("ERROR in githubLogin.js backend function =>", error.message);
// serverError({
// component: "/api/social-login/github-auth/catch-error",
// message: error.message,
// user: user,
// });
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return gitHubUser;
}
module.exports = githubLogin;
File diff suppressed because it is too large Load Diff
+105 -105
View File
@@ -1,105 +1,105 @@
/**
* Imports
* ==============================================================================
*/
const https = require("https");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main Function
* ==============================================================================
* @param {{
* url?: string,
* method: string,
* hostname: string,
* path?: string,
* href?: string,
* headers?: object,
* body?: object,
* }} params - params
*/
function httpsRequest({ url, method, hostname, path, href, headers, body }) {
const reqPayloadString = body ? JSON.stringify(body) : null;
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
let requestOptions = {
method: method,
hostname: hostname,
port: 443,
headers: {},
};
if (path) requestOptions.path = path;
if (href) requestOptions.href = href;
if (headers) requestOptions.headers = headers;
if (body) {
requestOptions.headers["Content-Type"] = "application/json";
requestOptions.headers["Content-Length"] = Buffer.from(reqPayloadString || "").length;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return new Promise((res, rej) => {
const httpsRequest = https.request(
/* ====== Request Options object ====== */
// @ts-ignore
url ? url : requestOptions,
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
/* ====== Callback function ====== */
(response) => {
var str = "";
// ## another chunk of data has been received, so append it to `str`
response.on("data", function (chunk) {
str += chunk;
});
// ## the whole response has been received, so we just print it out here
response.on("end", function () {
res(str);
});
response.on("error", (error) => {
console.log("HTTP response error =>", error.message);
});
}
);
if (body) httpsRequest.write(reqPayloadString);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
});
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
module.exports = httpsRequest;
/**
* Imports
* ==============================================================================
*/
const https = require("https");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main Function
* ==============================================================================
* @param {{
* url?: string,
* method: string,
* hostname: string,
* path?: string,
* href?: string,
* headers?: object,
* body?: object,
* }} params - params
*/
function httpsRequest({ url, method, hostname, path, href, headers, body }) {
const reqPayloadString = body ? JSON.stringify(body) : null;
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
let requestOptions = {
method: method,
hostname: hostname,
port: 443,
headers: {},
};
if (path) requestOptions.path = path;
if (href) requestOptions.href = href;
if (headers) requestOptions.headers = headers;
if (body) {
requestOptions.headers["Content-Type"] = "application/json";
requestOptions.headers["Content-Length"] = Buffer.from(reqPayloadString || "").length;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return new Promise((res, rej) => {
const httpsRequest = https.request(
/* ====== Request Options object ====== */
// @ts-ignore
url ? url : requestOptions,
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
/* ====== Callback function ====== */
(response) => {
var str = "";
// ## another chunk of data has been received, so append it to `str`
response.on("data", function (chunk) {
str += chunk;
});
// ## the whole response has been received, so we just print it out here
response.on("end", function () {
res(str);
});
response.on("error", (error) => {
console.log("HTTP response error =>", error.message);
});
}
);
if (body) httpsRequest.write(reqPayloadString);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
});
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
module.exports = httpsRequest;
+85 -85
View File
@@ -1,85 +1,85 @@
// @ts-check
const updateDbEntry = require("../query/utils/updateDbEntry");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {*} params.payload - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localUpdateUser({ payload, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
/**
* Initialize Variables
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
const data = (() => {
const reqBodyKeys = Object.keys(payload);
const finalData = {};
reqBodyKeys.forEach((key) => {
if (key?.match(/^date_|^id$/)) return;
// @ts-ignore
finalData[key] = payload[key];
});
return finalData;
})();
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
const updateUser = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: "users",
identifierColumnName: "id",
identifierValue: payload.id,
data: data,
encryptionKey,
encryptionSalt,
tableSchema,
});
return {
success: true,
payload: updateUser,
};
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local add-user Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localUpdateUser;
// @ts-check
const updateDbEntry = require("../query/utils/updateDbEntry");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {*} params.payload - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localUpdateUser({ payload, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
/**
* Initialize Variables
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
const data = (() => {
const reqBodyKeys = Object.keys(payload);
const finalData = {};
reqBodyKeys.forEach((key) => {
if (key?.match(/^date_|^id$/)) return;
// @ts-ignore
finalData[key] = payload[key];
});
return finalData;
})();
const tableSchema = dbSchema.tables.find((tb) => tb?.tableName === "users");
const updateUser = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: "users",
identifierColumnName: "id",
identifierValue: payload.id,
data: data,
encryptionKey,
encryptionSalt,
tableSchema,
});
return {
success: true,
payload: updateUser,
};
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local add-user Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localUpdateUser;