Updates
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||
type Param = {
|
||||
query: {
|
||||
invite: number;
|
||||
database_access: string;
|
||||
priviledge: string;
|
||||
email: string;
|
||||
};
|
||||
useLocal?: boolean;
|
||||
user: DATASQUIREL_LoggedInUser;
|
||||
};
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description this function handles admin users that have been invited by another
|
||||
* admin user. This fires when the invited user has been logged in or a new account
|
||||
* has been created for the invited user
|
||||
*/
|
||||
export default function addAdminUserOnLogin({ query, user, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,110 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addAdminUserOnLogin;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description this function handles admin users that have been invited by another
|
||||
* admin user. This fires when the invited user has been logged in or a new account
|
||||
* has been created for the invited user
|
||||
*/
|
||||
function addAdminUserOnLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, user, useLocal, }) {
|
||||
try {
|
||||
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER_1.default : DB_HANDLER_1.default;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||
const lastInviteTimeValues = [invite, email];
|
||||
const lastInviteTimeArray = yield finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||
const invitingUserDbValues = [invite];
|
||||
const invitingUserDb = yield finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||
const existingUserUser = yield finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
||||
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
||||
console.log("User already added");
|
||||
}
|
||||
else {
|
||||
(0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
data: {
|
||||
user_id: invite,
|
||||
invited_user_id: user.id,
|
||||
database_access: database_access,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
phone: user.phone,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
user_type: "admin",
|
||||
user_priviledge: priviledge,
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const dbTableData = yield finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
const clearEntries = yield finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
if (dbTableData && dbTableData[0]) {
|
||||
const dbTableEntries = dbTableData[0].db_tables_data.split("|");
|
||||
for (let i = 0; i < dbTableEntries.length; i++) {
|
||||
const dbTableEntry = dbTableEntries[i];
|
||||
const dbTableEntryArray = dbTableEntry.split("-");
|
||||
const [db_slug, table_slug] = dbTableEntryArray;
|
||||
const newEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "delegated_user_tables",
|
||||
data: {
|
||||
delegated_user_id: user.id,
|
||||
root_user_id: invite,
|
||||
database: db_slug,
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
type Param = {
|
||||
userId: number | string;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*/
|
||||
export default function addMariadbUser({ userId, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,72 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addMariadbUser;
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const NO_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/NO_DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const encrypt_1 = __importDefault(require("../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*/
|
||||
function addMariadbUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, useLocal, }) {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
const username = `dsql_user_${userId}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||
if (useLocal) {
|
||||
yield (0, LOCAL_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||
}
|
||||
else {
|
||||
yield (0, NO_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||
}
|
||||
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
||||
const updateUserValues = [username, encryptedPassword, userId];
|
||||
const updateUser = useLocal
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(updateUserQuery, updateUserValues)
|
||||
: yield (0, DB_HANDLER_1.default)(updateUserQuery, updateUserValues);
|
||||
const addMariadbUser = yield (0, addDbEntry_1.default)({
|
||||
tableName: "mariadb_users",
|
||||
data: {
|
||||
user_id: userId,
|
||||
username,
|
||||
host: defaultMariadbUserHost,
|
||||
password: encryptedPassword,
|
||||
primary: "1",
|
||||
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||
},
|
||||
dbContext: "Master",
|
||||
useLocal,
|
||||
});
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
userId: number;
|
||||
database: string;
|
||||
useLocal?: boolean;
|
||||
payload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function addUsersTableToDb({ userId, database, useLocal, payload, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,83 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addUsersTableToDb;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
||||
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function addUsersTableToDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, useLocal, payload, }) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload });
|
||||
if (!userPreset)
|
||||
throw new Error("Couldn't Get User Preset!");
|
||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||
if (!userSchemaData)
|
||||
throw new Error("User schema data not found!");
|
||||
let targetDatabase = userSchemaData.find((db) => db.dbFullName === database);
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users");
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
}
|
||||
else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||
/** @type {any[] | null} */
|
||||
const targetDb = useLocal
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||
: yield (0, DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
||||
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||
const newTableEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { CheckApiCredentialsFn } from "../../types";
|
||||
/**
|
||||
* # Grap API Credentials
|
||||
*/
|
||||
declare const grabApiCred: CheckApiCredentialsFn;
|
||||
export default grabApiCred;
|
||||
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||
/**
|
||||
* # Grap API Credentials
|
||||
*/
|
||||
const grabApiCred = ({ key, database, table, user_id, media, }) => {
|
||||
var _a, _b;
|
||||
if (!key)
|
||||
return null;
|
||||
if (!user_id)
|
||||
return null;
|
||||
try {
|
||||
const allowedKeysPath = process.env.DSQL_API_KEYS_PATH;
|
||||
if (!allowedKeysPath)
|
||||
throw new Error("process.env.DSQL_API_KEYS_PATH variable not found");
|
||||
const ApiJSON = (0, decrypt_1.default)({ encryptedString: key });
|
||||
/** @type {import("../../types").ApiKeyObject} */
|
||||
const ApiObject = JSON.parse(ApiJSON || "");
|
||||
const isApiKeyValid = fs_1.default.existsSync(`${allowedKeysPath}/${ApiObject.sign}`);
|
||||
if (String(ApiObject.user_id) !== String(user_id))
|
||||
return null;
|
||||
if (!isApiKeyValid)
|
||||
return null;
|
||||
if (!ApiObject.target_database)
|
||||
return ApiObject;
|
||||
if (media)
|
||||
return ApiObject;
|
||||
if (!database && ApiObject.target_database)
|
||||
return null;
|
||||
const isDatabaseAllowed = (_a = ApiObject.target_database) === null || _a === void 0 ? void 0 : _a.split(",").includes(String(database));
|
||||
if (isDatabaseAllowed && !ApiObject.target_table)
|
||||
return ApiObject;
|
||||
if (isDatabaseAllowed && !table && ApiObject.target_table)
|
||||
return null;
|
||||
const isTableAllowed = (_b = ApiObject.target_table) === null || _b === void 0 ? void 0 : _b.split(",").includes(String(table));
|
||||
if (isTableAllowed)
|
||||
return ApiObject;
|
||||
return null;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-cred ERROR: ${error.message}`);
|
||||
return { error: `api-cred ERROR: ${error.message}` };
|
||||
}
|
||||
};
|
||||
exports.default = grabApiCred;
|
||||
@@ -0,0 +1,23 @@
|
||||
export declare const grabAuthDirs: () => {
|
||||
root: string;
|
||||
auth: string;
|
||||
};
|
||||
export declare const initAuthFiles: () => boolean;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
*/
|
||||
export declare const writeAuthFile: (name: string, data: string) => boolean;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
*/
|
||||
export declare const getAuthFile: (name: string) => string | null;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export declare const deleteAuthFile: (name: string) => void | null;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export declare const checkAuthFile: (name: string) => boolean;
|
||||
@@ -0,0 +1,90 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.checkAuthFile = exports.deleteAuthFile = exports.getAuthFile = exports.writeAuthFile = exports.initAuthFiles = exports.grabAuthDirs = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grabAuthDirs = () => {
|
||||
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
|
||||
const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./))
|
||||
? DSQL_AUTH_DIR
|
||||
: path_1.default.resolve(process.cwd(), "./.tmp");
|
||||
const AUTH_DIR = path_1.default.join(ROOT_DIR, "logins");
|
||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||
};
|
||||
exports.grabAuthDirs = grabAuthDirs;
|
||||
const initAuthFiles = () => {
|
||||
try {
|
||||
const authDirs = (0, exports.grabAuthDirs)();
|
||||
if (!fs_1.default.existsSync(authDirs.root))
|
||||
fs_1.default.mkdirSync(authDirs.root, { recursive: true });
|
||||
if (!fs_1.default.existsSync(authDirs.auth))
|
||||
fs_1.default.mkdirSync(authDirs.auth, { recursive: true });
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.initAuthFiles = initAuthFiles;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
*/
|
||||
const writeAuthFile = (name, data) => {
|
||||
(0, exports.initAuthFiles)();
|
||||
try {
|
||||
fs_1.default.writeFileSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name), data);
|
||||
return true;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error writing Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.writeAuthFile = writeAuthFile;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
*/
|
||||
const getAuthFile = (name) => {
|
||||
try {
|
||||
const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name);
|
||||
return fs_1.default.readFileSync(authFilePath, "utf-8");
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error getting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
exports.getAuthFile = getAuthFile;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const deleteAuthFile = (name) => {
|
||||
try {
|
||||
return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error deleting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
exports.deleteAuthFile = deleteAuthFile;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const checkAuthFile = (name) => {
|
||||
try {
|
||||
return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||
return true;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error checking Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.checkAuthFile = checkAuthFile;
|
||||
@@ -0,0 +1,14 @@
|
||||
type Param = {
|
||||
database?: string;
|
||||
userId?: string | number;
|
||||
};
|
||||
type Return = {
|
||||
keyCookieName: string;
|
||||
csrfCookieName: string;
|
||||
oneTimeCodeName: string;
|
||||
};
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*/
|
||||
export default function getAuthCookieNames(params?: Param): Return;
|
||||
export {};
|
||||
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getAuthCookieNames;
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*/
|
||||
function getAuthCookieNames(params) {
|
||||
var _a, _b;
|
||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||
const cookieOneTimeCodeName = process.env.DSQL_COOKIES_ONE_TIME_CODE_NAME || "one-time-code";
|
||||
const targetDatabase = ((_a = params === null || params === void 0 ? void 0 : params.database) === null || _a === void 0 ? void 0 : _a.replace(/^datasquirel_user_\d+_/, "")) ||
|
||||
((_b = process.env.DSQL_DB_NAME) === null || _b === void 0 ? void 0 : _b.replace(/^datasquirel_user_\d+_/, ""));
|
||||
let keyCookieName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
keyCookieName += `user_${params.userId}_`;
|
||||
if (targetDatabase)
|
||||
keyCookieName += `${targetDatabase}_`;
|
||||
keyCookieName += cookiesKeyName;
|
||||
let csrfCookieName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
csrfCookieName += `user_${params.userId}_`;
|
||||
if (targetDatabase)
|
||||
csrfCookieName += `${targetDatabase}_`;
|
||||
csrfCookieName += cookiesCSRFName;
|
||||
let oneTimeCodeName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
oneTimeCodeName += `user_${params.userId}_`;
|
||||
if (targetDatabase)
|
||||
oneTimeCodeName += `${targetDatabase}_`;
|
||||
oneTimeCodeName += cookieOneTimeCodeName;
|
||||
return {
|
||||
keyCookieName,
|
||||
csrfCookieName,
|
||||
oneTimeCodeName,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
type Param = {
|
||||
dbContext?: "Master" | "Dsql User";
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName?: string;
|
||||
tableName: string;
|
||||
data: any;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
duplicateColumnName?: string;
|
||||
duplicateColumnValue?: string;
|
||||
update?: boolean;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} [params.dbFullName] - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
||||
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
||||
* @param {boolean} [params.update] - Update this row if it exists
|
||||
* @param {string} [params.encryptionKey] - Update this row if it exists
|
||||
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export default function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,209 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addDbEntry;
|
||||
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
||||
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
||||
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} [params.dbFullName] - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
||||
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
||||
* @param {boolean} [params.update] - Update this row if it exists
|
||||
* @param {string} [params.encryptionKey] - Update this row if it exists
|
||||
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function addDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }) {
|
||||
var _b, _c;
|
||||
/**
|
||||
* Initialize variables
|
||||
*/
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
/** @type { any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (data === null || data === void 0 ? void 0 : data["date_created_timestamp"])
|
||||
delete data["date_created_timestamp"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_updated_timestamp"])
|
||||
delete data["date_updated_timestamp"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_updated"])
|
||||
delete data["date_updated"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_updated_code"])
|
||||
delete data["date_updated_code"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_created"])
|
||||
delete data["date_created"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_created_code"])
|
||||
delete data["date_created_code"];
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Handle function logic
|
||||
*/
|
||||
if (duplicateColumnName && typeof duplicateColumnName === "string") {
|
||||
const duplicateValue = isMaster
|
||||
? yield dbHandler(`SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`, [duplicateColumnValue])
|
||||
: yield dbHandler({
|
||||
paradigm: "Read Only",
|
||||
database: dbFullName,
|
||||
queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
queryValues: [duplicateColumnValue],
|
||||
});
|
||||
if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) {
|
||||
return null;
|
||||
}
|
||||
else if (duplicateValue && duplicateValue[0] && update) {
|
||||
return yield (0, updateDbEntry_1.default)({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
identifierColumnName: duplicateColumnName,
|
||||
identifierValue: duplicateColumnValue || "",
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
let insertKeysArray = [];
|
||||
let insertValuesArray = [];
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
// @ts-ignore
|
||||
let value = data === null || data === void 0 ? void 0 : data[dataKey];
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName == dataKey)
|
||||
: null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
if (value == null || value == undefined)
|
||||
continue;
|
||||
if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) &&
|
||||
typeof value == "string" &&
|
||||
!(value === null || value === void 0 ? void 0 : value.match(/./)))
|
||||
continue;
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
console.log("DSQL: Encrypted value =>", value);
|
||||
}
|
||||
const htmlRegex = /<[^>]+>/g;
|
||||
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
|
||||
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
||||
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
||||
if (!pattern.test(value)) {
|
||||
console.log("DSQL: Pattern not matched =>", value);
|
||||
value = "";
|
||||
}
|
||||
}
|
||||
insertKeysArray.push("`" + dataKey + "`");
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
if (typeof value == "number") {
|
||||
insertValuesArray.push(String(value));
|
||||
}
|
||||
else {
|
||||
insertValuesArray.push(value);
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_created"])) {
|
||||
insertKeysArray.push("`date_created`");
|
||||
insertValuesArray.push(Date());
|
||||
}
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_created_code"])) {
|
||||
insertKeysArray.push("`date_created_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_updated"])) {
|
||||
insertKeysArray.push("`date_updated`");
|
||||
insertValuesArray.push(Date());
|
||||
}
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_updated_code"])) {
|
||||
insertKeysArray.push("`date_updated_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
////////////////////////////////////////
|
||||
const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
||||
const queryValuesArray = insertValuesArray;
|
||||
const newInsert = isMaster
|
||||
? yield dbHandler(query, queryValuesArray)
|
||||
: yield dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return newInsert;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
type Param = {
|
||||
dbContext?: string;
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
identifierColumnName: string;
|
||||
identifierValue: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Delete DB Entry Function
|
||||
* @description
|
||||
*/
|
||||
export default function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: Param): Promise<object | null>;
|
||||
export {};
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = deleteDbEntry;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Delete DB Entry Function
|
||||
* @description
|
||||
*/
|
||||
function deleteDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }) {
|
||||
try {
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
/** @type { (a1:any, a2?:any) => any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
||||
const deletedEntry = isMaster
|
||||
? yield dbHandler(query, [identifierValue])
|
||||
: yield dbHandler({
|
||||
paradigm,
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValues: [identifierValue],
|
||||
});
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
}
|
||||
catch (error) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
* @returns {string}
|
||||
*/
|
||||
export default function pathTraversalCheck(text: string | number): string;
|
||||
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = pathTraversalCheck;
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
* @returns {string}
|
||||
*/
|
||||
function pathTraversalCheck(text) {
|
||||
return text.toString().replace(/\//g, "");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
query: string | any;
|
||||
readOnly?: boolean;
|
||||
local?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
queryValuesArray?: (string | number)[];
|
||||
tableName?: string;
|
||||
};
|
||||
/**
|
||||
* # Run DSQL users queries
|
||||
*/
|
||||
export default function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,155 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = runQuery;
|
||||
const fullAccessDbHandler_1 = __importDefault(require("../fullAccessDbHandler"));
|
||||
const varReadOnlyDatabaseDbHandler_1 = __importDefault(require("../varReadOnlyDatabaseDbHandler"));
|
||||
const serverError_1 = __importDefault(require("../serverError"));
|
||||
const addDbEntry_1 = __importDefault(require("./addDbEntry"));
|
||||
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
|
||||
const deleteDbEntry_1 = __importDefault(require("./deleteDbEntry"));
|
||||
const trim_sql_1 = __importDefault(require("../../../utils/trim-sql"));
|
||||
/**
|
||||
* # Run DSQL users queries
|
||||
*/
|
||||
function runQuery(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let result;
|
||||
let error;
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
try {
|
||||
const table = tableName
|
||||
? tableName
|
||||
: typeof query == "string"
|
||||
? null
|
||||
: query
|
||||
? query === null || query === void 0 ? void 0 : query.table
|
||||
: null;
|
||||
if (!table)
|
||||
throw new Error("No table name provided");
|
||||
tableSchema = dbSchema.tables.filter((tb) => (tb === null || tb === void 0 ? void 0 : tb.tableName) === table)[0];
|
||||
}
|
||||
catch (_err) {
|
||||
// console.log("ERROR getting tableSchema: ", _err.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
try {
|
||||
if (typeof query === "string") {
|
||||
const formattedQuery = (0, trim_sql_1.default)(query);
|
||||
/**
|
||||
* Input Validation
|
||||
*
|
||||
* @description Input Validation
|
||||
*/
|
||||
if (readOnly &&
|
||||
formattedQuery.match(/^alter|^delete|information_schema|^create/i)) {
|
||||
throw new Error("Wrong Input!");
|
||||
}
|
||||
if (readOnly) {
|
||||
result = yield (0, varReadOnlyDatabaseDbHandler_1.default)({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
}
|
||||
else {
|
||||
result = yield (0, fullAccessDbHandler_1.default)({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
local,
|
||||
});
|
||||
}
|
||||
}
|
||||
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 = yield (0, addDbEntry_1.default)({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
update,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
if (!(result === null || result === void 0 ? void 0 : result.insertId)) {
|
||||
error = new Error("Couldn't insert data");
|
||||
}
|
||||
break;
|
||||
case "update":
|
||||
result = yield (0, updateDbEntry_1.default)({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
break;
|
||||
case "delete":
|
||||
result = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
result = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "functions/backend/runQuery",
|
||||
message: error.message,
|
||||
});
|
||||
result = null;
|
||||
error = error.message;
|
||||
}
|
||||
return { result, error };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*/
|
||||
declare function sanitizeSql(text: any, spaces: boolean, regex?: RegExp | null): any;
|
||||
export default sanitizeSql;
|
||||
@@ -0,0 +1,111 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*/
|
||||
function sanitizeSql(text, spaces, regex) {
|
||||
var _a;
|
||||
if (!text)
|
||||
return "";
|
||||
if (typeof text == "number" || typeof text == "boolean")
|
||||
return text;
|
||||
if (typeof text == "string" && !((_a = text === null || text === void 0 ? void 0 : text.toString()) === null || _a === void 0 ? void 0 : _a.match(/./)))
|
||||
return "";
|
||||
if (typeof text == "object" && !Array.isArray(text)) {
|
||||
const newObject = sanitizeObjects(text, spaces);
|
||||
return newObject;
|
||||
}
|
||||
else if (typeof text == "object" && Array.isArray(text)) {
|
||||
const newArray = sanitizeArrays(text, spaces);
|
||||
return newArray;
|
||||
}
|
||||
let finalText = text;
|
||||
if (regex) {
|
||||
finalText = text.toString().replace(regex, "");
|
||||
}
|
||||
if (spaces) {
|
||||
}
|
||||
else {
|
||||
finalText = text
|
||||
.toString()
|
||||
.replace(/\n|\r|\n\r|\r\n/g, "")
|
||||
.replace(/ /g, "");
|
||||
}
|
||||
const escapeRegex = /select |insert |drop |delete |alter |create |exec | union | or | like | concat|LOAD_FILE|ASCII| COLLATE | HAVING | information_schema|DECLARE |\#|WAITFOR |delay |BENCHMARK |\/\*.*\*\//gi;
|
||||
finalText = finalText
|
||||
.replace(/(?<!\\)\'/g, "\\'")
|
||||
.replace(/(?<!\\)\`/g, "\\`")
|
||||
.replace(/\/\*\*\//g, "")
|
||||
.replace(escapeRegex, "\\$&");
|
||||
return finalText;
|
||||
}
|
||||
/**
|
||||
* Sanitize Objects Function
|
||||
* ==============================================================================
|
||||
* @description Sanitize objects in the form { key: "value" }
|
||||
*
|
||||
* @param {any} object - Database Full Name
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
function sanitizeObjects(object, spaces) {
|
||||
/** @type {any} */
|
||||
let objectUpdated = Object.assign({}, object);
|
||||
const keys = Object.keys(objectUpdated);
|
||||
keys.forEach((key) => {
|
||||
const value = objectUpdated[key];
|
||||
if (!value) {
|
||||
delete objectUpdated[key];
|
||||
return;
|
||||
}
|
||||
if (typeof value == "string" || typeof value == "number") {
|
||||
objectUpdated[key] = sanitizeSql(value, spaces);
|
||||
}
|
||||
else if (typeof value == "object" && !Array.isArray(value)) {
|
||||
objectUpdated[key] = sanitizeObjects(value, spaces);
|
||||
}
|
||||
else if (typeof value == "object" && Array.isArray(value)) {
|
||||
objectUpdated[key] = sanitizeArrays(value, spaces);
|
||||
}
|
||||
});
|
||||
return objectUpdated;
|
||||
}
|
||||
/**
|
||||
* Sanitize Objects Function
|
||||
* ==============================================================================
|
||||
* @description Sanitize objects in the form { key: "value" }
|
||||
*
|
||||
* @param {any[]} array - Database Full Name
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
*
|
||||
* @returns {string[]|number[]|object[]}
|
||||
*/
|
||||
function sanitizeArrays(array, spaces) {
|
||||
let arrayUpdated = lodash_1.default.cloneDeep(array);
|
||||
arrayUpdated.forEach((item, index) => {
|
||||
const value = item;
|
||||
if (!value) {
|
||||
arrayUpdated.splice(index, 1);
|
||||
return;
|
||||
}
|
||||
if (typeof item == "string" || typeof item == "number") {
|
||||
arrayUpdated[index] = sanitizeSql(value, spaces);
|
||||
}
|
||||
else if (typeof item == "object" && !Array.isArray(value)) {
|
||||
arrayUpdated[index] = sanitizeObjects(value, spaces);
|
||||
}
|
||||
else if (typeof item == "object" && Array.isArray(value)) {
|
||||
arrayUpdated[index] = sanitizeArrays(item, spaces);
|
||||
}
|
||||
});
|
||||
return arrayUpdated;
|
||||
}
|
||||
exports.default = sanitizeSql;
|
||||
@@ -0,0 +1,19 @@
|
||||
type Param = {
|
||||
dbContext?: "Master" | "Dsql User";
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName?: string;
|
||||
tableName: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
data: any;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
identifierColumnName: string;
|
||||
identifierValue: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
export default function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<object | null>;
|
||||
export {};
|
||||
@@ -0,0 +1,144 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateDbEntry;
|
||||
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
||||
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
function updateDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
if (!data || !Object.keys(data).length)
|
||||
return null;
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
/** @type {(a1:any, a2?:any)=> any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
let updateKeyValueArray = [];
|
||||
let updateValues = [];
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
// @ts-ignore
|
||||
let value = data[dataKey];
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName === dataKey)
|
||||
: null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
if (value == null || value == undefined)
|
||||
continue;
|
||||
const htmlRegex = /<[^>]+>/g;
|
||||
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
|
||||
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
||||
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
||||
if (!pattern.test(value)) {
|
||||
console.log("DSQL: Pattern not matched =>", value);
|
||||
value = "";
|
||||
}
|
||||
}
|
||||
if (typeof value === "string" && value.match(/^null$/i)) {
|
||||
value = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
if (typeof value === "string" && !value.match(/./i)) {
|
||||
value = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
updateKeyValueArray.push(`\`${dataKey}\`=?`);
|
||||
if (typeof value == "number") {
|
||||
updateValues.push(String(value));
|
||||
}
|
||||
else {
|
||||
updateValues.push(value);
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */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 = isMaster
|
||||
? yield dbHandler(query, updateValues)
|
||||
: yield dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: updateValues,
|
||||
});
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return updatedEntry;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
export default function dbHandler(...args: any[]): Promise<any>;
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = dbHandler;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
|
||||
const grabDbSSL_1 = __importDefault(require("../../utils/backend/grabDbSSL"));
|
||||
const connection = (0, serverless_mysql_1.default)({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
function dbHandler(...args) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a;
|
||||
((_a = process.env.NODE_ENV) === null || _a === void 0 ? void 0 : _a.match(/dev/)) &&
|
||||
fs_1.default.appendFileSync("./.tmp/sqlQuery.sql", args[0] + "\n" + Date() + "\n\n\n", "utf8");
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = yield new Promise((resolve, reject) => {
|
||||
connection.query(...args, (error, result, fields) => {
|
||||
if (error) {
|
||||
resolve({ error: error.message });
|
||||
}
|
||||
else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
yield connection.end();
|
||||
}
|
||||
catch (error) {
|
||||
fs_1.default.appendFileSync("./.tmp/dbErrorLogs.txt", JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
results = null;
|
||||
(0, serverError_1.default)({
|
||||
component: "dbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
declare const defaultFieldsRegexp: RegExp;
|
||||
export default defaultFieldsRegexp;
|
||||
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
exports.default = defaultFieldsRegexp;
|
||||
@@ -0,0 +1,12 @@
|
||||
type Param = {
|
||||
queryString: string;
|
||||
database: string;
|
||||
local?: boolean;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType | null;
|
||||
queryValuesArray?: string[];
|
||||
};
|
||||
/**
|
||||
* # Full Access Db Handler
|
||||
*/
|
||||
export default function fullAccessDbHandler({ queryString, database, tableSchema, queryValuesArray, local, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = fullAccessDbHandler;
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
/**
|
||||
* # Full Access Db Handler
|
||||
*/
|
||||
function fullAccessDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, database, tableSchema, queryValuesArray, local, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
results = local
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(queryString, queryValuesArray)
|
||||
: yield (0, DSQL_USER_DB_HANDLER_1.default)({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
(0, serverError_1.default)({
|
||||
component: "fullAccessDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = yield (0, parseDbResults_1.default)({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
else if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { DSQL_TableSchemaType } from "../../types";
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function grabNewUsersTableSchema(params: {
|
||||
payload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
}): DSQL_TableSchemaType | null;
|
||||
@@ -0,0 +1,42 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabNewUsersTableSchema;
|
||||
const grabSchemaFieldsFromData_1 = __importDefault(require("./grabSchemaFieldsFromData"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function grabNewUsersTableSchema(params) {
|
||||
try {
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
const defaultFields = require("../../data/defaultFields.json");
|
||||
const supplementalFields = (params === null || params === void 0 ? void 0 : params.payload)
|
||||
? (0, grabSchemaFieldsFromData_1.default)({
|
||||
data: params === null || params === void 0 ? void 0 : params.payload,
|
||||
excludeData: defaultFields,
|
||||
excludeFields: userPreset.fields,
|
||||
})
|
||||
: [];
|
||||
console.log("supplementalFields", supplementalFields);
|
||||
const allFields = [...userPreset.fields, ...supplementalFields];
|
||||
console.log("allFields", allFields);
|
||||
const finalFields = [
|
||||
...defaultFields.slice(0, 2),
|
||||
...allFields,
|
||||
...defaultFields.slice(2),
|
||||
];
|
||||
userPreset.fields = [...finalFields];
|
||||
return userPreset;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "grabNewUsersTableSchema",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { DSQL_FieldSchemaType } from "../../types";
|
||||
type Param = {
|
||||
data?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
fields?: string[];
|
||||
excludeData?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
excludeFields?: DSQL_FieldSchemaType[];
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function grabSchemaFieldsFromData({ data, fields, excludeData, excludeFields, }: Param): DSQL_FieldSchemaType[];
|
||||
export {};
|
||||
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabSchemaFieldsFromData;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function grabSchemaFieldsFromData({ data, fields, excludeData, excludeFields, }) {
|
||||
var _a;
|
||||
try {
|
||||
const possibleFields = require("../../data/possibleFields.json");
|
||||
const dataTypes = require("../../data/dataTypes.json");
|
||||
/** @type {DSQL_FieldSchemaType[]} */
|
||||
const finalFields = [];
|
||||
/** @type {string[]} */
|
||||
let filteredFields = [];
|
||||
if (data && ((_a = Object.keys(data)) === null || _a === void 0 ? void 0 : _a[0])) {
|
||||
filteredFields = Object.keys(data);
|
||||
}
|
||||
if (fields) {
|
||||
filteredFields = [...filteredFields, ...fields];
|
||||
filteredFields = [...new Set(filteredFields)];
|
||||
}
|
||||
filteredFields = filteredFields
|
||||
.filter((fld) => !excludeData || !Object.keys(excludeData).includes(fld))
|
||||
.filter((fld) => !excludeFields ||
|
||||
!excludeFields.find((exlFld) => exlFld.fieldName == fld));
|
||||
filteredFields.forEach((fld) => {
|
||||
const value = data ? data[fld] : null;
|
||||
if (typeof value == "string") {
|
||||
const newField = {
|
||||
fieldName: fld,
|
||||
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
||||
};
|
||||
if (Boolean(value.match(/<[^>]+>/g))) {
|
||||
newField.richText = true;
|
||||
}
|
||||
finalFields.push(newField);
|
||||
}
|
||||
else if (typeof value == "number") {
|
||||
finalFields.push({
|
||||
fieldName: fld,
|
||||
dataType: "INT",
|
||||
});
|
||||
}
|
||||
else {
|
||||
finalFields.push({
|
||||
fieldName: fld,
|
||||
dataType: "VARCHAR(255)",
|
||||
});
|
||||
}
|
||||
});
|
||||
return finalFields;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "grabSchemaFieldsFromData.js",
|
||||
message: error.message,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* # Grab User Schema Data
|
||||
*/
|
||||
export default function grabUserSchemaData({ userId, }: {
|
||||
userId: string | number;
|
||||
}): import("../../types").DSQL_DatabaseSchemaType[] | null;
|
||||
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabUserSchemaData;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
/**
|
||||
* # Grab User Schema Data
|
||||
*/
|
||||
function grabUserSchemaData({ userId, }) {
|
||||
try {
|
||||
const userSchemaFilePath = path_1.default.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
|
||||
const userSchemaData = JSON.parse(fs_1.default.readFileSync(userSchemaFilePath, "utf-8"));
|
||||
return userSchemaData;
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "grabUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
to?: string;
|
||||
subject?: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
senderName?: string;
|
||||
alias?: string | null;
|
||||
};
|
||||
/**
|
||||
* # Handle mails With Nodemailer
|
||||
*/
|
||||
export default function handleNodemailer({ to, subject, text, html, alias, senderName, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,89 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = handleNodemailer;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
let transporter = nodemailer_1.default.createTransport({
|
||||
host: process.env.DSQL_MAIL_HOST,
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.DSQL_MAIL_EMAIL,
|
||||
pass: process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Handle mails With Nodemailer
|
||||
*/
|
||||
function handleNodemailer(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ to, subject, text, html, alias, senderName, }) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!process.env.DSQL_MAIL_HOST ||
|
||||
!process.env.DSQL_MAIL_EMAIL ||
|
||||
!process.env.DSQL_MAIL_PASSWORD) {
|
||||
return null;
|
||||
}
|
||||
const sender = (() => {
|
||||
if (alias === null || alias === void 0 ? void 0 : alias.match(/support/i))
|
||||
return process.env.DSQL_MAIL_EMAIL;
|
||||
return process.env.DSQL_MAIL_EMAIL;
|
||||
})();
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
let sentMessage;
|
||||
if (!fs_1.default.existsSync("./email/index.html")) {
|
||||
return;
|
||||
}
|
||||
let mailRoot = fs_1.default.readFileSync("./email/index.html", "utf8");
|
||||
let finalHtml = mailRoot
|
||||
.replace(/{{email_body}}/, html ? html : "")
|
||||
.replace(/{{issue_date}}/, Date().substring(0, 24));
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
try {
|
||||
let mailObject = {};
|
||||
mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`;
|
||||
mailObject["sender"] = sender;
|
||||
if (alias)
|
||||
mailObject["replyTo"] = sender;
|
||||
mailObject["to"] = to;
|
||||
mailObject["subject"] = subject;
|
||||
mailObject["text"] = text;
|
||||
mailObject["html"] = finalHtml;
|
||||
// send mail with defined transport object
|
||||
let info = yield transporter.sendMail(mailObject);
|
||||
sentMessage = info;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
console.log("ERROR in handleNodemailer Function =>", error.message);
|
||||
// serverError({
|
||||
// component: "handleNodemailer",
|
||||
// message: error.message,
|
||||
// user: { email: to },
|
||||
// });
|
||||
}
|
||||
return sentMessage;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
declare const sanitizeHtmlOptions: {
|
||||
allowedTags: string[];
|
||||
allowedAttributes: {
|
||||
a: string[];
|
||||
img: string[];
|
||||
"*": string[];
|
||||
};
|
||||
};
|
||||
export default sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const sanitizeHtmlOptions = {
|
||||
allowedTags: [
|
||||
"b",
|
||||
"i",
|
||||
"em",
|
||||
"strong",
|
||||
"a",
|
||||
"p",
|
||||
"span",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"img",
|
||||
"div",
|
||||
"button",
|
||||
"pre",
|
||||
"code",
|
||||
"br",
|
||||
],
|
||||
allowedAttributes: {
|
||||
a: ["href"],
|
||||
img: ["src", "alt", "width", "height", "class", "style"],
|
||||
"*": ["style", "class"],
|
||||
},
|
||||
};
|
||||
exports.default = sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { HttpFunctionResponse, HttpRequestParams } from "../../types";
|
||||
/**
|
||||
* # Generate a http Request
|
||||
*/
|
||||
export default function httpRequest<ReqObj extends {
|
||||
[k: string]: any;
|
||||
} = {
|
||||
[k: string]: any;
|
||||
}, ResObj extends {
|
||||
[k: string]: any;
|
||||
} = {
|
||||
[k: string]: any;
|
||||
}>(params: HttpRequestParams<ReqObj>): Promise<HttpFunctionResponse<ResObj>>;
|
||||
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = httpRequest;
|
||||
const node_http_1 = __importDefault(require("node:http"));
|
||||
const node_https_1 = __importDefault(require("node:https"));
|
||||
const querystring_1 = __importDefault(require("querystring"));
|
||||
const serialize_query_1 = __importDefault(require("../../utils/serialize-query"));
|
||||
/**
|
||||
* # Generate a http Request
|
||||
*/
|
||||
function httpRequest(params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isUrlEncodedFormBody = params.urlEncodedFormBody;
|
||||
const reqPayloadString = params.body
|
||||
? isUrlEncodedFormBody
|
||||
? querystring_1.default.stringify(params.body)
|
||||
: JSON.stringify(params.body).replace(/\n|\r|\n\r/gm, "")
|
||||
: undefined;
|
||||
const reqQueryString = params.query
|
||||
? (0, serialize_query_1.default)(params.query)
|
||||
: undefined;
|
||||
const paramScheme = params.scheme;
|
||||
const finalScheme = paramScheme == "http" ? node_http_1.default : node_https_1.default;
|
||||
const finalPath = params.path
|
||||
? params.path + (reqQueryString ? reqQueryString : "")
|
||||
: undefined;
|
||||
delete params.body;
|
||||
delete params.scheme;
|
||||
delete params.query;
|
||||
delete params.urlEncodedFormBody;
|
||||
/** @type {import("node:https").RequestOptions} */
|
||||
const requestOptions = Object.assign(Object.assign({}, params), { headers: Object.assign({ "Content-Type": isUrlEncodedFormBody
|
||||
? "application/x-www-form-urlencoded"
|
||||
: "application/json", "Content-Length": reqPayloadString
|
||||
? Buffer.from(reqPayloadString).length
|
||||
: undefined }, params.headers), port: paramScheme == "https" ? 443 : params.port, path: finalPath });
|
||||
const httpsRequest = finalScheme.request(requestOptions,
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
const data = (() => {
|
||||
try {
|
||||
const jsonObj = JSON.parse(str);
|
||||
return jsonObj;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
resolve({
|
||||
status: response.statusCode || 404,
|
||||
data,
|
||||
str,
|
||||
requestedPath: finalPath,
|
||||
});
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve({
|
||||
status: response.statusCode || 404,
|
||||
str,
|
||||
error: err.message,
|
||||
requestedPath: finalPath,
|
||||
});
|
||||
});
|
||||
});
|
||||
if (reqPayloadString) {
|
||||
httpsRequest.write(reqPayloadString);
|
||||
}
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
type Param = {
|
||||
scheme?: string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
hostname?: string;
|
||||
path?: string;
|
||||
port?: number | string;
|
||||
headers?: object;
|
||||
body?: object;
|
||||
};
|
||||
/**
|
||||
* # Make Https Request
|
||||
*/
|
||||
export default function httpsRequest({ url, method, hostname, path, headers, body, port, scheme, }: Param): Promise<unknown>;
|
||||
export {};
|
||||
@@ -0,0 +1,88 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = httpsRequest;
|
||||
const https_1 = __importDefault(require("https"));
|
||||
const http_1 = __importDefault(require("http"));
|
||||
const url_1 = require("url");
|
||||
/**
|
||||
* # Make Https Request
|
||||
*/
|
||||
function httpsRequest({ url, method, hostname, path, headers, body, port, scheme, }) {
|
||||
var _a;
|
||||
const reqPayloadString = body ? JSON.stringify(body) : null;
|
||||
const PARSED_URL = url ? new url_1.URL(url) : null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
/** @type {any} */
|
||||
let requestOptions = {
|
||||
method: method || "GET",
|
||||
hostname: PARSED_URL ? PARSED_URL.hostname : hostname,
|
||||
port: (scheme === null || scheme === void 0 ? void 0 : scheme.match(/https/i))
|
||||
? 443
|
||||
: PARSED_URL
|
||||
? ((_a = PARSED_URL.protocol) === null || _a === void 0 ? void 0 : _a.match(/https/i))
|
||||
? 443
|
||||
: PARSED_URL.port
|
||||
: port
|
||||
? Number(port)
|
||||
: 80,
|
||||
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"] = reqPayloadString
|
||||
? Buffer.from(reqPayloadString).length
|
||||
: undefined;
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return new Promise((res, rej) => {
|
||||
var _a;
|
||||
const httpsRequest = ((scheme === null || scheme === void 0 ? void 0 : scheme.match(/https/i))
|
||||
? https_1.default
|
||||
: ((_a = PARSED_URL === null || PARSED_URL === void 0 ? void 0 : PARSED_URL.protocol) === null || _a === void 0 ? void 0 : _a.match(/https/i))
|
||||
? https_1.default
|
||||
: http_1.default).request(
|
||||
/* ====== Request Options object ====== */
|
||||
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);
|
||||
rej(`HTTP response error =>, ${error.message}`);
|
||||
});
|
||||
response.on("close", () => {
|
||||
console.log("HTTP(S) Response Closed Successfully");
|
||||
});
|
||||
});
|
||||
if (body)
|
||||
httpsRequest.write(reqPayloadString);
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error.message);
|
||||
rej(`HTTP request error =>, ${error.message}`);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* # No Database DB Handler
|
||||
*/
|
||||
export default function noDatabaseDbHandler(queryString: string): Promise<any>;
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = noDatabaseDbHandler;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const NO_DB_HANDLER_1 = __importDefault(require("../../../package-shared/utils/backend/global-db/NO_DB_HANDLER"));
|
||||
/**
|
||||
* # No Database DB Handler
|
||||
*/
|
||||
function noDatabaseDbHandler(queryString) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a;
|
||||
((_a = process.env.NODE_ENV) === null || _a === void 0 ? void 0 : _a.match(/dev/)) &&
|
||||
fs_1.default.appendFileSync("./.tmp/sqlQuery.sql", queryString + "\n" + Date() + "\n\n\n", "utf8");
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
results = yield (0, NO_DB_HANDLER_1.default)(queryString);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "noDatabaseDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
unparsedResults: any[];
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
};
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
export default function parseDbResults({ unparsedResults, tableSchema, }: Param): Promise<any[] | null>;
|
||||
export {};
|
||||
@@ -0,0 +1,76 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = parseDbResults;
|
||||
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||
const defaultFieldsRegexp_1 = __importDefault(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
|
||||
*/
|
||||
function parseDbResults(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ unparsedResults, tableSchema, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let parsedResults = [];
|
||||
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 === null || tableSchema === void 0 ? void 0 : tableSchema.fields[i];
|
||||
if (resultFieldName === null || resultFieldName === void 0 ? void 0 : resultFieldName.match(defaultFieldsRegexp_1.default)) {
|
||||
continue;
|
||||
}
|
||||
let value = result[resultFieldName];
|
||||
if (typeof value !== "number" && !value) {
|
||||
// parsedResults.push(result);
|
||||
continue;
|
||||
}
|
||||
if (resultFieldSchema === null || resultFieldSchema === void 0 ? void 0 : resultFieldSchema.encrypted) {
|
||||
if (value === null || value === void 0 ? void 0 : value.match(/./)) {
|
||||
result[resultFieldName] = (0, decrypt_1.default)({
|
||||
encryptedString: value,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
parsedResults.push(result);
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
return parsedResults;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in parseDbResults Function =>", error.message);
|
||||
return unparsedResults;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { IncomingMessage } from "http";
|
||||
type Param = {
|
||||
user?: {
|
||||
id?: number | string;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
email?: string;
|
||||
} & any;
|
||||
message: string;
|
||||
component?: string;
|
||||
noMail?: boolean;
|
||||
req?: import("next").NextApiRequest & IncomingMessage;
|
||||
};
|
||||
/**
|
||||
* # Server Error
|
||||
*/
|
||||
export default function serverError({ user, message, component, noMail, req, }: Param): Promise<void>;
|
||||
export {};
|
||||
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = serverError;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
/**
|
||||
* # Server Error
|
||||
*/
|
||||
function serverError(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ user, message, component, noMail, req, }) {
|
||||
const date = new Date();
|
||||
const reqIp = (() => {
|
||||
if (!req)
|
||||
return null;
|
||||
try {
|
||||
const forwarded = req.headers["x-forwarded-for"];
|
||||
const realIp = req.headers["x-real-ip"];
|
||||
const cloudflareIp = req.headers["cf-connecting-ip"];
|
||||
// Convert forwarded IPs to string and get the first IP if multiple exist
|
||||
const forwardedIp = Array.isArray(forwarded)
|
||||
? forwarded[0]
|
||||
: forwarded === null || forwarded === void 0 ? void 0 : forwarded.split(",")[0];
|
||||
const clientIp = cloudflareIp ||
|
||||
forwardedIp ||
|
||||
realIp ||
|
||||
req.socket.remoteAddress;
|
||||
if (!clientIp)
|
||||
return null;
|
||||
return String(clientIp);
|
||||
}
|
||||
catch (error) {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
try {
|
||||
let log = `🚀 SERVER ERROR ===========================\nError Message: ${message}\nComponent: ${component}`;
|
||||
if ((user === null || user === void 0 ? void 0 : user.id) && (user === null || user === void 0 ? void 0 : user.first_name) && (user === null || user === void 0 ? void 0 : user.last_name) && (user === null || user === void 0 ? void 0 : user.email)) {
|
||||
log += `\nUser Id: ${user === null || user === void 0 ? void 0 : user.id}\nUser Name: ${user === null || user === void 0 ? void 0 : user.first_name} ${user === null || user === void 0 ? void 0 : user.last_name}\nUser Email: ${user === null || user === void 0 ? void 0 : user.email}`;
|
||||
}
|
||||
if (req === null || req === void 0 ? void 0 : req.url) {
|
||||
log += `\nURL: ${req.url}`;
|
||||
}
|
||||
if (req === null || req === void 0 ? void 0 : req.body) {
|
||||
log += `\nRequest Body: ${JSON.stringify(req.body, null, 4)}`;
|
||||
}
|
||||
if (reqIp) {
|
||||
log += `\nIP: ${reqIp}`;
|
||||
}
|
||||
log += `\nDate: ${date.toDateString()}`;
|
||||
log += "\n========================================";
|
||||
if (!fs_1.default.existsSync(`./.tmp/error.log`)) {
|
||||
fs_1.default.writeFileSync(`./.tmp/error.log`, "", "utf-8");
|
||||
}
|
||||
const initialText = fs_1.default.readFileSync(`./.tmp/error.log`, "utf-8");
|
||||
fs_1.default.writeFileSync(`./.tmp/error.log`, log);
|
||||
fs_1.default.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("Server Error Reporting Error:", error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -0,0 +1,16 @@
|
||||
import { DSQL_DatabaseSchemaType } from "../../types";
|
||||
type Param = {
|
||||
userId: string | number;
|
||||
schemaData: DSQL_DatabaseSchemaType[];
|
||||
};
|
||||
/**
|
||||
* # Set User Schema Data
|
||||
*/
|
||||
export default function setUserSchemaData({ userId, schemaData, }: Param): boolean;
|
||||
export {};
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = setUserSchemaData;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
/**
|
||||
* # Set User Schema Data
|
||||
*/
|
||||
function setUserSchemaData({ userId, schemaData, }) {
|
||||
try {
|
||||
const userSchemaFilePath = path_1.default.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
|
||||
fs_1.default.writeFileSync(userSchemaFilePath, JSON.stringify(schemaData), "utf8");
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/functions/backend/setUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,8 @@
|
||||
import { IncomingMessage } from "http";
|
||||
export default function (req: IncomingMessage): Promise<{
|
||||
email: string;
|
||||
password: string;
|
||||
authKey: string;
|
||||
logged_in_status: boolean;
|
||||
date: number;
|
||||
} | null>;
|
||||
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("./cookies/get-auth-cookie-names"));
|
||||
function default_1(req) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const { keyCookieName, csrfCookieName } = (0, get_auth_cookie_names_1.default)();
|
||||
const suKeyName = `${keyCookieName}_su`;
|
||||
const cookies = (0, parseCookies_1.default)({ request: req });
|
||||
if (!(cookies === null || cookies === void 0 ? void 0 : cookies[suKeyName])) {
|
||||
return null;
|
||||
}
|
||||
/** ********************* Grab the payload */
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
encryptedString: cookies[suKeyName],
|
||||
});
|
||||
/** ********************* Return if no payload */
|
||||
if (!userPayload)
|
||||
return null;
|
||||
/** ********************* Parse the payload */
|
||||
let userObject = JSON.parse(userPayload);
|
||||
if (userObject.password !== process.env.DSQL_USER_KEY)
|
||||
return null;
|
||||
if (userObject.authKey !== process.env.DSQL_SPECIAL_KEY)
|
||||
return null;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/** ********************* return user object */
|
||||
return userObject;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
userId: number | string;
|
||||
database: string;
|
||||
newFields?: string[];
|
||||
newPayload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function updateUsersTableSchema({ userId, database, newFields, newPayload, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateUsersTableSchema;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
||||
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||
const grabSchemaFieldsFromData_1 = __importDefault(require("./grabSchemaFieldsFromData"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function updateUsersTableSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, newFields, newPayload, }) {
|
||||
var _b, _c;
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||
if (!userSchemaData)
|
||||
throw new Error("User schema data not found!");
|
||||
let targetDatabaseIndex = userSchemaData.findIndex((db) => db.dbFullName === database);
|
||||
if (targetDatabaseIndex < 0) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
let existingTableIndex = (_b = userSchemaData[targetDatabaseIndex]) === null || _b === void 0 ? void 0 : _b.tables.findIndex((table) => table.tableName === "users");
|
||||
const usersTable = userSchemaData[targetDatabaseIndex].tables[existingTableIndex];
|
||||
if (!((_c = usersTable === null || usersTable === void 0 ? void 0 : usersTable.fields) === null || _c === void 0 ? void 0 : _c[0]))
|
||||
throw new Error("Users Table Not Found!");
|
||||
const additionalFields = (0, grabSchemaFieldsFromData_1.default)({
|
||||
fields: newFields,
|
||||
data: newPayload,
|
||||
});
|
||||
const spliceStartIndex = usersTable.fields.findIndex((field) => field.fieldName === "date_created");
|
||||
const finalSpliceStartIndex = spliceStartIndex >= 0 ? spliceStartIndex : 0;
|
||||
usersTable.fields.splice(finalSpliceStartIndex, 0, ...additionalFields);
|
||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
type Param = {
|
||||
queryString: string;
|
||||
queryValuesArray?: any[];
|
||||
database?: string;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
export default function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = varDatabaseDbHandler;
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
function varDatabaseDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, queryValuesArray, database, tableSchema, useLocal, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))
|
||||
? true
|
||||
: false;
|
||||
/** @type {any} */
|
||||
const FINAL_DB_HANDLER = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (queryString &&
|
||||
queryValuesArray &&
|
||||
Array.isArray(queryValuesArray) &&
|
||||
queryValuesArray[0]) {
|
||||
results = isMaster
|
||||
? yield FINAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: yield FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
}
|
||||
else {
|
||||
results = isMaster
|
||||
? yield FINAL_DB_HANDLER(queryString)
|
||||
: yield FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "varDatabaseDbHandler/lines-29-32",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
try {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = yield (0, parseDbResults_1.default)({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
|
||||
(0, serverError_1.default)({
|
||||
component: "varDatabaseDbHandler/lines-52-53",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
else if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
queryString: string;
|
||||
database: string;
|
||||
queryValuesArray?: string[];
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Read Only Db Handler with Varaibles
|
||||
* @returns
|
||||
*/
|
||||
export default function varReadOnlyDatabaseDbHandler({ queryString, database, queryValuesArray, tableSchema, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,78 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = varReadOnlyDatabaseDbHandler;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Read Only Db Handler with Varaibles
|
||||
* @returns
|
||||
*/
|
||||
function varReadOnlyDatabaseDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, database, queryValuesArray, tableSchema, useLocal, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = useLocal
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(queryString, queryValuesArray)
|
||||
: yield (0, DSQL_USER_DB_HANDLER_1.default)({
|
||||
paradigm: "Read Only",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
(0, serverError_1.default)({
|
||||
component: "varReadOnlyDatabaseDbHandler",
|
||||
message: error.message,
|
||||
noMail: true,
|
||||
});
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = yield (0, parseDbResults_1.default)({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user