This commit is contained in:
Benjamin Toby
2025-07-05 14:59:30 +01:00
parent 6e334c2525
commit 7e8bb37c09
526 changed files with 17560 additions and 11386 deletions
@@ -0,0 +1,10 @@
import { SiteConfig } from "../../../types";
type Params = {
userId?: string | number;
};
type Return = {
appConfig: SiteConfig;
userConfig: SiteConfig | null;
};
export default function grabConfig(params?: Params): Return;
export {};
+24
View File
@@ -0,0 +1,24 @@
import fs from "fs";
import grabDirNames from "../names/grab-dir-names";
import EJSON from "../../ejson";
import envsub from "../../envsub";
export default function grabConfig(params) {
const { appConfigJSONFile, userConfigJSONFilePath } = grabDirNames({
userId: params === null || params === void 0 ? void 0 : params.userId,
});
const appConfigJSON = envsub(fs.readFileSync(appConfigJSONFile, "utf-8"));
const appConfig = EJSON.parse(appConfigJSON);
if (!userConfigJSONFilePath) {
return { appConfig, userConfig: null };
}
if (!fs.existsSync(userConfigJSONFilePath)) {
fs.writeFileSync(userConfigJSONFilePath, JSON.stringify({
main: {},
}), "utf-8");
}
const userConfigJSON = envsub(fs.readFileSync(userConfigJSONFilePath, "utf-8"));
const userConfig = (EJSON.parse(userConfigJSON) || {
main: {},
});
return { appConfig, userConfig };
}
@@ -0,0 +1,10 @@
import { SiteConfigMain } from "../../../types";
type Params = {
userId?: string | number;
};
type Return = {
appMainConfig: SiteConfigMain;
userMainConfig?: SiteConfigMain;
};
export default function grabMainConfig(params?: Params): Return;
export {};
@@ -0,0 +1,6 @@
import grabConfig from "./grab-config";
export default function grabMainConfig(params) {
const { appConfig } = grabConfig();
const { userConfig } = grabConfig({ userId: params === null || params === void 0 ? void 0 : params.userId });
return { appMainConfig: appConfig.main, userMainConfig: userConfig === null || userConfig === void 0 ? void 0 : userConfig.main };
}
@@ -0,0 +1,11 @@
import { SiteConfig } from "../../../types";
type Params = {
userId?: string | number;
newConfig?: SiteConfig;
};
type Return = {
success?: boolean;
msg?: string;
};
export default function updateUserConfig({ newConfig, userId, }: Params): Return;
export {};
@@ -0,0 +1,25 @@
import fs from "fs";
import grabDirNames from "../names/grab-dir-names";
import grabConfig from "./grab-config";
import _ from "lodash";
export default function updateUserConfig({ newConfig, userId, }) {
if (!userId || !newConfig) {
return {
success: false,
msg: `UserID or newConfig not provided`,
};
}
const { userConfigJSONFilePath } = grabDirNames({
userId,
});
if (!userConfigJSONFilePath || !fs.existsSync(userConfigJSONFilePath)) {
return {
success: false,
msg: `userConfigJSONFilePath not found!`,
};
}
const { userConfig: existingUserConfig } = grabConfig({ userId });
const updateConfig = _.merge(existingUserConfig, newConfig);
fs.writeFileSync(userConfigJSONFilePath, JSON.stringify(updateConfig), "utf-8");
return { success: true };
}
@@ -1,13 +1,7 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exportMariadbDatabase;
const child_process_1 = require("child_process");
const os_1 = __importDefault(require("os"));
function exportMariadbDatabase({ dbFullName, targetFilePath, mariadbHost, mariadbPass, mariadbUser, }) {
const mysqlDumpPath = os_1.default.platform().match(/win/i)
import { execSync } from "child_process";
import os from "os";
export default function exportMariadbDatabase({ dbFullName, targetFilePath, mariadbHost, mariadbPass, mariadbUser, }) {
const mysqlDumpPath = os.platform().match(/win/i)
? "'" +
"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" +
"'"
@@ -19,6 +13,6 @@ function exportMariadbDatabase({ dbFullName, targetFilePath, mariadbHost, mariad
let execSyncOptions = {
encoding: "utf-8",
};
const dumpDb = (0, child_process_1.execSync)(cmd, execSyncOptions);
const dumpDb = execSync(cmd, execSyncOptions);
return dumpDb;
}
+20 -37
View File
@@ -1,42 +1,25 @@
"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 = DB_HANDLER;
const grab_dsql_connection_1 = __importDefault(require("../../grab-dsql-connection"));
import grabDSQLConnection from "../../grab-dsql-connection";
/**
* # DSQL user read-only DB handler
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
*/
function DB_HANDLER(...args) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const CONNECTION = (0, grab_dsql_connection_1.default)();
try {
if (!CONNECTION)
throw new Error("No Connection provided to DB_HANDLER function!");
const results = yield CONNECTION.query(...args);
return JSON.parse(JSON.stringify(results));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `DB_HANDLER Error`, error);
return {
success: false,
error: error.message,
};
}
finally {
yield (CONNECTION === null || CONNECTION === void 0 ? void 0 : CONNECTION.end());
}
});
export default async function DB_HANDLER(...args) {
var _a;
const CONNECTION = grabDSQLConnection();
try {
if (!CONNECTION)
throw new Error("No Connection provided to DB_HANDLER function!");
const results = await CONNECTION.query(...args);
return JSON.parse(JSON.stringify(results));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `DB_HANDLER Error`, error);
return {
success: false,
error: error.message,
};
}
finally {
await (CONNECTION === null || CONNECTION === void 0 ? void 0 : CONNECTION.end());
}
}
@@ -1,38 +1,21 @@
"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 = DSQL_USER_DB_HANDLER;
const conn_db_handler_1 = __importDefault(require("../../db/conn-db-handler"));
const grab_dsql_connection_1 = __importDefault(require("../../grab-dsql-connection"));
import connDbHandler from "../../db/conn-db-handler";
import grabDSQLConnection from "../../grab-dsql-connection";
/**
* # DSQL user read-only DB handler
*/
function DSQL_USER_DB_HANDLER(_a) {
return __awaiter(this, arguments, void 0, function* ({ paradigm, queryString, queryValues, }) {
var _b;
const CONNECTION = paradigm == "Read Only"
? (0, grab_dsql_connection_1.default)({ ro: true })
: (0, grab_dsql_connection_1.default)({ fa: true });
try {
return yield (0, conn_db_handler_1.default)(CONNECTION, queryString, queryValues);
}
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `DSQL_USER_DB_HANDLER Error`, error);
return null;
}
finally {
CONNECTION === null || CONNECTION === void 0 ? void 0 : CONNECTION.end();
}
});
export default async function DSQL_USER_DB_HANDLER({ paradigm, queryString, queryValues, }) {
var _a;
const CONNECTION = paradigm == "Read Only"
? grabDSQLConnection({ ro: true })
: grabDSQLConnection({ fa: true });
try {
return await connDbHandler(CONNECTION, queryString, queryValues);
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `DSQL_USER_DB_HANDLER Error`, error);
return null;
}
finally {
CONNECTION === null || CONNECTION === void 0 ? void 0 : CONNECTION.end();
}
}
@@ -1,39 +1,22 @@
"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 = LOCAL_DB_HANDLER;
const grab_dsql_connection_1 = __importDefault(require("../../grab-dsql-connection"));
import grabDSQLConnection from "../../grab-dsql-connection";
/**
* # DSQL user read-only DB handler
*/
function LOCAL_DB_HANDLER(...args) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const MASTER = (0, grab_dsql_connection_1.default)();
try {
const results = yield MASTER.query(...args);
return JSON.parse(JSON.stringify(results));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `LOCAL_DB_HANDLER Error`, error);
return {
success: false,
error: error.message,
};
}
finally {
yield (MASTER === null || MASTER === void 0 ? void 0 : MASTER.end());
}
});
export default async function LOCAL_DB_HANDLER(...args) {
var _a;
const MASTER = grabDSQLConnection();
try {
const results = await MASTER.query(...args);
return JSON.parse(JSON.stringify(results));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `LOCAL_DB_HANDLER Error`, error);
return {
success: false,
error: error.message,
};
}
finally {
await (MASTER === null || MASTER === void 0 ? void 0 : MASTER.end());
}
}
@@ -1,16 +1,10 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = NO_DB_HANDLER;
const grab_dsql_connection_1 = __importDefault(require("../../grab-dsql-connection"));
import grabDSQLConnection from "../../grab-dsql-connection";
/**
* # DSQL user read-only DB handler
*/
function NO_DB_HANDLER(...args) {
export default function NO_DB_HANDLER(...args) {
var _a;
const CONNECTION = (0, grab_dsql_connection_1.default)();
const CONNECTION = grabDSQLConnection();
try {
return new Promise((resolve, reject) => {
CONNECTION.query(...args)
@@ -1,16 +1,10 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ROOT_DB_HANDLER;
const grab_dsql_connection_1 = __importDefault(require("../../grab-dsql-connection"));
import grabDSQLConnection from "../../grab-dsql-connection";
/**
* # Root DB handler
*/
function ROOT_DB_HANDLER(...args) {
export default function ROOT_DB_HANDLER(...args) {
var _a;
const CONNECTION = (0, grab_dsql_connection_1.default)();
const CONNECTION = grabDSQLConnection();
try {
return new Promise((resolve, reject) => {
CONNECTION.query(...args)
+4 -10
View File
@@ -1,25 +1,19 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabDbSSL;
const fs_1 = __importDefault(require("fs"));
import fs from "fs";
/**
* # Grall SSL
*/
function grabDbSSL() {
export default function grabDbSSL() {
const SSL_DIR = process.env.DSQL_SSL_DIR;
if (!(SSL_DIR === null || SSL_DIR === void 0 ? void 0 : SSL_DIR.match(/./))) {
return undefined;
}
const caFilePath = `${SSL_DIR}/ca-cert.pem`;
if (!fs_1.default.existsSync(caFilePath)) {
if (!fs.existsSync(caFilePath)) {
console.log(`${caFilePath} does not exist`);
return undefined;
}
return {
ca: fs_1.default.readFileSync(`${SSL_DIR}/ca-cert.pem`),
ca: fs.readFileSync(`${SSL_DIR}/ca-cert.pem`),
// key: fs.readFileSync(`${SSL_DIR}/client-key.pem`),
// cert: fs.readFileSync(`${SSL_DIR}/client-cert.pem`),
rejectUnauthorized: false,
+19 -36
View File
@@ -1,37 +1,20 @@
"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 = importMariadbDatabase;
const child_process_1 = require("child_process");
const os_1 = __importDefault(require("os"));
const conn_db_handler_1 = __importDefault(require("../db/conn-db-handler"));
function importMariadbDatabase(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, targetFilePath, mariadbHost, mariadbPass, mariadbUser, }) {
const mysqlPath = os_1.default.platform().match(/win/i)
? "'" +
"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" +
"'"
: "mysql";
const finalMariadbUser = mariadbUser || process.env.DSQL_DB_USERNAME;
const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST;
const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD;
yield (0, conn_db_handler_1.default)(global.DSQL_DB_CONN, `CREATE DATABASE IF NOT EXISTS ${dbFullName}`);
const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p"${finalMariadbPass}" ${dbFullName} < ${targetFilePath}`;
let execSyncOptions = {
encoding: "utf-8",
};
const importDb = (0, child_process_1.execSync)(cmd, execSyncOptions);
return importDb;
});
import { execSync } from "child_process";
import os from "os";
import connDbHandler from "../db/conn-db-handler";
export default async function importMariadbDatabase({ dbFullName, targetFilePath, mariadbHost, mariadbPass, mariadbUser, }) {
const mysqlPath = os.platform().match(/win/i)
? "'" +
"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" +
"'"
: "mysql";
const finalMariadbUser = mariadbUser || process.env.DSQL_DB_USERNAME;
const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST;
const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD;
await connDbHandler(global.DSQL_DB_CONN, `CREATE DATABASE IF NOT EXISTS ${dbFullName}`);
const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p"${finalMariadbPass}" ${dbFullName} < ${targetFilePath}`;
let execSyncOptions = {
encoding: "utf-8",
};
const importDb = execSync(cmd, execSyncOptions);
return importDb;
}
@@ -1,8 +0,0 @@
import { DATASQUIREL_LoggedInUser, UserType } from "../../../types";
type Param = {
user?: DATASQUIREL_LoggedInUser | UserType;
userId?: string | number | null;
dbSlug?: string;
};
export default function grabUserDbFullName({ dbSlug, user, userId }: Param): string;
export {};
@@ -1,12 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabUserDbFullName;
function grabUserDbFullName({ dbSlug, user, userId }) {
const finalUserId = (user === null || user === void 0 ? void 0 : user.id) || userId;
if (!finalUserId || !dbSlug)
throw new Error(`Couldn't grab full DB name. Missing parameters finalUserId || dbSlug`);
if (dbSlug.match(/[^a-zA-Z0-9-_]/)) {
throw new Error(`Invalid Database slug`);
}
return `datasquirel_user_${finalUserId}_${dbSlug}`;
}
+32 -3
View File
@@ -3,17 +3,19 @@ type Param = {
user?: DATASQUIREL_LoggedInUser | UserType;
userId?: string | number | null;
appDir?: string;
dataDir?: string;
};
export default function grabDirNames(param?: Param): {
appDir: string;
schemasDir: string;
userDirPath: string | undefined;
privateDataDir: string;
oldSchemasDir: string;
userConfigJSONFilePath: string | undefined;
mainShemaJSONFilePath: string;
mainDbTypeDefFile: string;
tempDirName: string;
defaultTableFieldsJSONFilePath: string;
usersSchemaDir: string;
targetUserSchemaDir: string | undefined;
targetUserPrivateDir: string | undefined;
userSchemaMainJSONFilePath: string | undefined;
userPrivateMediaDir: string | undefined;
userPrivateExportsDir: string | undefined;
@@ -36,5 +38,32 @@ export default function grabDirNames(param?: Param): {
testEnvFile: string;
userPublicMediaDir: string | undefined;
userTempSQLFilePath: string | undefined;
STATIC_ROOT: string;
appConfigJSONFile: string;
appConfigDir: string;
mariadbMainConfigDir: string;
mariadbMainConfigFile: string;
maxscaleConfigDir: string;
mariadbReplicaConfigDir: string;
DATA_DIR: string;
publicDir: string;
publicSSLDir: string;
appSSLDir: string;
maxscaleConfigFile: string;
mariadbReplicaConfigFile: string;
mainSSLDir: string;
mainDbDataDir: string;
replica1DbDataDir: string;
galeraConfigFile: string;
galeraReplicaConfigFile: string;
dbDockerComposeFile: string;
dbDockerComposeFileAlt: string;
mainDbGrastateDatFile: string;
appSchemaJSONFile: string;
mainBackupDir: string;
userBackupDir: string | undefined;
sqlBackupDirName: string;
schemasBackupDirName: string;
userMainShemaJSONFilePath: string | undefined;
};
export {};
+115 -49
View File
@@ -1,86 +1,125 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabDirNames;
const path_1 = __importDefault(require("path"));
function grabDirNames(param) {
import path from "path";
export default function grabDirNames(param) {
var _a;
const appDir = (param === null || param === void 0 ? void 0 : param.appDir) || process.env.DSQL_APP_DIR;
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR || "/static";
const DATA_DIR = (param === null || param === void 0 ? void 0 : param.dataDir) || process.env.DSQL_DATA_DIR || "/data";
const finalUserId = ((_a = param === null || param === void 0 ? void 0 : param.user) === null || _a === void 0 ? void 0 : _a.id) || (param === null || param === void 0 ? void 0 : param.userId);
const publicImagesDir = path_1.default.join(STATIC_ROOT, `images`);
if (!appDir)
throw new Error("Please provide the `DSQL_APP_DIR` env variable.");
const schemasDir = process.env.DSQL_DB_SCHEMA_DIR ||
path_1.default.join(appDir, "jsonData", "dbSchemas");
if (!DATA_DIR)
throw new Error("Please provide the `DATA_DIR` env variable.");
const STATIC_ROOT = path.join(DATA_DIR, "static");
const publicImagesDir = path.join(STATIC_ROOT, `images`);
const publicDir = path.join(appDir, "public");
const publicSSLDir = path.join(publicDir, "documents", "ssl");
const appSSLDir = path.join(appDir, "ssl");
const mainSSLDir = path.join(DATA_DIR, "ssl");
const privateDataDir = path.join(DATA_DIR, "private");
/**
* # DB Dir names
* @description Database related Directories
*/
const mainDbDataDir = path.join(DATA_DIR, "db");
const mainDbGrastateDatFile = path.join(mainDbDataDir, "grastate.dat");
const replica1DbDataDir = path.join(DATA_DIR, "replica-1");
const mariadbMainConfigDir = path.join(DATA_DIR, "db-config", "main");
const mariadbReplicaConfigDir = path.join(DATA_DIR, "db-config", "replica");
const maxscaleConfigDir = path.join(DATA_DIR, "db-config", "maxscale");
const mariadbMainConfigFile = path.join(mariadbMainConfigDir, "default.cnf");
const mariadbReplicaConfigFile = path.join(mariadbReplicaConfigDir, "default.cnf");
const galeraConfigFile = path.join(mariadbMainConfigDir, "galera.cnf");
const galeraReplicaConfigFile = path.join(mariadbReplicaConfigDir, "galera.cnf");
const maxscaleConfigFile = path.join(maxscaleConfigDir, "maxscale.cnf");
/**
* # Schema Dir names
* @description
*/
const oldSchemasDir = path.join(appDir, "jsonData", "dbSchemas");
const appSchemaJSONFile = path.join(oldSchemasDir, "1.json");
const tempDirName = ".tmp";
if (!schemasDir)
const appConfigDir = path.join(appDir, "jsonData", "config");
const appConfigJSONFile = path.join(appConfigDir, "app-config.json");
if (!privateDataDir)
throw new Error("Please provide the `DSQL_DB_SCHEMA_DIR` env variable.");
const pakageSharedDir = path_1.default.join(appDir, `package-shared`);
const mainDbTypeDefFile = path_1.default.join(pakageSharedDir, `types/dsql.ts`);
const mainShemaJSONFilePath = path_1.default.join(schemasDir, `main.json`);
const defaultTableFieldsJSONFilePath = path_1.default.join(pakageSharedDir, `data/defaultFields.json`);
const usersSchemaDir = path_1.default.join(schemasDir, `users`);
const targetUserSchemaDir = finalUserId
? path_1.default.join(usersSchemaDir, `user-${finalUserId}`)
const pakageSharedDir = path.join(appDir, `package-shared`);
const mainDbTypeDefFile = path.join(pakageSharedDir, `types/dsql.ts`);
const mainShemaJSONFilePath = path.join(oldSchemasDir, `main.json`);
const defaultTableFieldsJSONFilePath = path.join(pakageSharedDir, `data/defaultFields.json`);
const usersSchemaDir = path.join(privateDataDir, `users`);
const targetUserPrivateDir = finalUserId
? path.join(usersSchemaDir, `user-${finalUserId}`)
: undefined;
const userTempSQLFilePath = targetUserSchemaDir
? path_1.default.join(targetUserSchemaDir, `tmp.sql`)
const userTempSQLFilePath = targetUserPrivateDir
? path.join(targetUserPrivateDir, `tmp.sql`)
: undefined;
const userDirPath = finalUserId
? path_1.default.join(usersSchemaDir, `user-${finalUserId}`)
const userMainShemaJSONFilePath = targetUserPrivateDir
? path.join(targetUserPrivateDir, `main.json`)
: undefined;
const userSchemaMainJSONFilePath = userDirPath
? path_1.default.join(userDirPath, `main.json`)
const userConfigJSONFilePath = targetUserPrivateDir
? path.join(targetUserPrivateDir, `config.json`)
: undefined;
const userPrivateMediaDir = userDirPath
? path_1.default.join(userDirPath, `media`)
const userSchemaMainJSONFilePath = targetUserPrivateDir
? path.join(targetUserPrivateDir, `main.json`)
: undefined;
const userPrivateExportsDir = userDirPath
? path_1.default.join(userDirPath, `export`)
const userPrivateMediaDir = targetUserPrivateDir
? path.join(targetUserPrivateDir, `media`)
: undefined;
const userPrivateExportsDir = targetUserPrivateDir
? path.join(targetUserPrivateDir, `export`)
: undefined;
const userPrivateSQLExportsDir = userPrivateExportsDir
? path_1.default.join(userPrivateExportsDir, `sql`)
? path.join(userPrivateExportsDir, `sql`)
: undefined;
const userPrivateTempSQLExportsDir = userPrivateSQLExportsDir
? path_1.default.join(userPrivateSQLExportsDir, tempDirName)
? path.join(userPrivateSQLExportsDir, tempDirName)
: undefined;
const userPrivateTempJSONSchemaFilePath = userPrivateTempSQLExportsDir
? path_1.default.join(userPrivateTempSQLExportsDir, `schema.json`)
? path.join(userPrivateTempSQLExportsDir, `schema.json`)
: undefined;
const userPrivateDbExportZipFileName = `db-export.zip`;
const userPrivateDbExportZipFilePath = userPrivateSQLExportsDir
? path_1.default.join(userPrivateSQLExportsDir, userPrivateDbExportZipFileName)
? path.join(userPrivateSQLExportsDir, userPrivateDbExportZipFileName)
: undefined;
const userPublicMediaDir = finalUserId
? path_1.default.join(publicImagesDir, `user-images/user-${finalUserId}`)
? path.join(publicImagesDir, `user-images/user-${finalUserId}`)
: undefined;
const userPrivateDbImportZipFileName = `db-export.zip`;
const userPrivateDbImportZipFilePath = userPrivateSQLExportsDir
? path_1.default.join(userPrivateSQLExportsDir, userPrivateDbImportZipFileName)
? path.join(userPrivateSQLExportsDir, userPrivateDbImportZipFileName)
: undefined;
const dbNginxLoadBalancerConfigFile = path_1.default.join(appDir, "docker/services/mariadb/load-balancer/config/template/nginx.conf");
let dockerComposeFile = path_1.default.join(appDir, "docker-compose.yml");
let dockerComposeFileAlt = path_1.default.join(appDir, "docker-compose.yaml");
const testDockerComposeFile = path_1.default.join(appDir, "test.docker-compose.yml");
const testDockerComposeFileAlt = path_1.default.join(appDir, "test.docker-compose.yaml");
const extraDockerComposeFile = path_1.default.join(appDir, "extra.docker-compose.yml");
const extraDockerComposeFileAlt = path_1.default.join(appDir, "extra.docker-compose.yaml");
const siteSetupFile = path_1.default.join(appDir, "site-setup.json");
const envFile = path_1.default.join(appDir, ".env");
const testEnvFile = path_1.default.join(appDir, "test.env");
const dbNginxLoadBalancerConfigFile = path.join(appDir, "docker/services/mariadb/load-balancer/config/template/nginx.conf");
let dockerComposeFile = path.join(appDir, "docker-compose.yml");
let dockerComposeFileAlt = path.join(appDir, "docker-compose.yaml");
const testDockerComposeFile = path.join(appDir, "test.docker-compose.yml");
const testDockerComposeFileAlt = path.join(appDir, "test.docker-compose.yaml");
const dbDockerComposeFile = path.join(appDir, "db.docker-compose.yml");
const dbDockerComposeFileAlt = path.join(appDir, "db.docker-compose.yaml");
const extraDockerComposeFile = path.join(appDir, "extra.docker-compose.yml");
const extraDockerComposeFileAlt = path.join(appDir, "extra.docker-compose.yaml");
const siteSetupFile = path.join(appDir, "site-setup.json");
const envFile = path.join(appDir, ".env");
const testEnvFile = path.join(appDir, "test.env");
/**
* # Backup Dir names
* @description
*/
const mainBackupDir = path.join(DATA_DIR, "backups");
const userBackupDir = targetUserPrivateDir
? path.join(targetUserPrivateDir, `backups`)
: undefined;
const sqlBackupDirName = `sql`;
const schemasBackupDirName = `schema`;
return {
appDir,
schemasDir,
userDirPath,
privateDataDir,
oldSchemasDir,
userConfigJSONFilePath,
mainShemaJSONFilePath,
mainDbTypeDefFile,
tempDirName,
defaultTableFieldsJSONFilePath,
usersSchemaDir,
targetUserSchemaDir,
targetUserPrivateDir,
userSchemaMainJSONFilePath,
userPrivateMediaDir,
userPrivateExportsDir,
@@ -103,5 +142,32 @@ function grabDirNames(param) {
testEnvFile,
userPublicMediaDir,
userTempSQLFilePath,
STATIC_ROOT,
appConfigJSONFile,
appConfigDir,
mariadbMainConfigDir,
mariadbMainConfigFile,
maxscaleConfigDir,
mariadbReplicaConfigDir,
DATA_DIR,
publicDir,
publicSSLDir,
appSSLDir,
maxscaleConfigFile,
mariadbReplicaConfigFile,
mainSSLDir,
mainDbDataDir,
replica1DbDataDir,
galeraConfigFile,
galeraReplicaConfigFile,
dbDockerComposeFile,
dbDockerComposeFileAlt,
mainDbGrastateDatFile,
appSchemaJSONFile,
mainBackupDir,
userBackupDir,
sqlBackupDirName,
schemasBackupDirName,
userMainShemaJSONFilePath,
};
}
@@ -0,0 +1,6 @@
export default function grabIPAddresses(): {
webAppIP: string;
appCronIP: string;
maxScaleIP: string;
globalIPPrefix: string;
};
@@ -0,0 +1,9 @@
import grabDockerResourceIPNumbers from "../../grab-docker-resource-ip-numbers";
export default function grabIPAddresses() {
const globalIPPrefix = process.env.DSQL_NETWORK_IP_PREFIX || "172.72.0";
const { cron, db, maxscale, postDbSetup, web } = grabDockerResourceIPNumbers();
const webAppIP = `${globalIPPrefix}.${web}`;
const appCronIP = `${globalIPPrefix}.${cron}`;
const maxScaleIP = `${globalIPPrefix}.${maxscale}`;
return { webAppIP, appCronIP, maxScaleIP, globalIPPrefix };
}
@@ -1,7 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = replaceDatasquirelDbName;
function replaceDatasquirelDbName({ str, userId, }) {
export default function replaceDatasquirelDbName({ str, userId, }) {
const dbNamePrefix = process.env.DSQL_USER_DB_PREFIX;
const userNameRegex = new RegExp(`${dbNamePrefix}\\d+_`, "g");
const newPrefix = `${dbNamePrefix}${userId}_`;
+1 -4
View File
@@ -1,6 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = parseCookies;
/**
* Parse request cookies
* ===================================================
@@ -8,7 +5,7 @@ exports.default = parseCookies;
* @description This function takes in a request object and
* returns the cookies as a JS object
*/
function parseCookies({ request, cookieString, }) {
export default function parseCookies({ request, cookieString, }) {
var _a;
try {
/** @type {string | undefined} */
+1 -4
View File
@@ -1,13 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = camelJoinedtoCamelSpace;
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*/
function camelJoinedtoCamelSpace(text) {
export default function camelJoinedtoCamelSpace(text) {
if (!(text === null || text === void 0 ? void 0 : text.match(/./))) {
return "";
}
+1 -4
View File
@@ -1,7 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = checkIfIsMaster;
function checkIfIsMaster({ dbContext, dbFullName }) {
export default function checkIfIsMaster({ dbContext, dbFullName }) {
return (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
? false
: global.DSQL_USE_LOCAL
+2 -5
View File
@@ -1,6 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ccol = void 0;
const consoleColors = {
Reset: "\x1b[0m",
Bright: "\x1b[1m",
@@ -28,5 +25,5 @@ const consoleColors = {
BgWhite: "\x1b[47m",
BgGray: "\x1b[100m",
};
exports.default = consoleColors;
exports.ccol = consoleColors;
export default consoleColors;
export const ccol = consoleColors;
+7
View File
@@ -0,0 +1,7 @@
import * as http from "http";
import { CookieOptions } from "../types";
import { CookieNames } from "../dict/cookie-names";
export declare function setCookie(res: http.ServerResponse, name: (typeof CookieNames)[keyof typeof CookieNames], value: string, options?: CookieOptions): void;
export declare function getCookie(req: http.IncomingMessage, name: (typeof CookieNames)[keyof typeof CookieNames]): string | null;
export declare function updateCookie(res: http.ServerResponse, name: (typeof CookieNames)[keyof typeof CookieNames], value: string, options?: CookieOptions): void;
export declare function deleteCookie(res: http.ServerResponse, name: (typeof CookieNames)[keyof typeof CookieNames], options?: CookieOptions): void;
+43
View File
@@ -0,0 +1,43 @@
export function setCookie(res, name, value, options = {}) {
const cookieParts = [
`${encodeURIComponent(name)}=${encodeURIComponent(value)}`,
];
if (options.expires) {
cookieParts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.maxAge !== undefined) {
cookieParts.push(`Max-Age=${options.maxAge}`);
}
if (options.path) {
cookieParts.push(`Path=${options.path}`);
}
if (options.domain) {
cookieParts.push(`Domain=${options.domain}`);
}
if (options.secure) {
cookieParts.push("Secure");
}
if (options.httpOnly) {
cookieParts.push("HttpOnly");
}
res.setHeader("Set-Cookie", cookieParts.join("; "));
}
export function getCookie(req, name) {
const cookieHeader = req.headers.cookie;
if (!cookieHeader)
return null;
const cookies = cookieHeader
.split(";")
.reduce((acc, cookie) => {
const [key, val] = cookie.trim().split("=").map(decodeURIComponent);
acc[key] = val;
return acc;
}, {});
return cookies[name] || null;
}
export function updateCookie(res, name, value, options = {}) {
setCookie(res, name, value, options);
}
export function deleteCookie(res, name, options = {}) {
setCookie(res, name, "", Object.assign(Object.assign({}, options), { expires: new Date(0), maxAge: 0 }));
}
+7
View File
@@ -0,0 +1,7 @@
import { UserType } from "../types";
export default function createUserSQLUser(user: UserType): Promise<{
fullName: string;
host: string;
username: string;
password: string;
}>;
+41
View File
@@ -0,0 +1,41 @@
import { generate } from "generate-password";
import dbHandler from "../functions/backend/dbHandler";
import dsqlCrud from "./data-fetching/crud";
import encrypt from "../functions/dsql/encrypt";
import grabUserMainSqlUserName from "./grab-user-main-sql-user-name";
import grabDbNames from "./grab-db-names";
import { createNewSQLUser } from "../functions/web-app/mariadb-user/handle-mariadb-user-creation";
export default async function createUserSQLUser(user) {
const { fullName, host, username: mariaDBUsername, webHost, } = grabUserMainSqlUserName({ user });
const { userDbPrefix } = grabDbNames({ user });
await dbHandler({
query: `DROP USER IF EXISTS '${mariaDBUsername}'@'${webHost}'`,
noErrorLogs: true,
});
const newPassword = generate({ length: 32 });
await createNewSQLUser({
host: webHost,
password: newPassword,
username: mariaDBUsername,
});
const updateWebHostGrants = (await dbHandler({
query: `GRANT ALL PRIVILEGES ON \`${userDbPrefix.replace(/\_/g, "\\_")}%\`.* TO '${mariaDBUsername}'@'${webHost}'`,
}));
const updateUser = await dsqlCrud({
action: "update",
table: "users",
targetField: "id",
targetValue: user.id,
data: {
mariadb_host: webHost,
mariadb_pass: encrypt({ data: newPassword }) || undefined,
mariadb_user: mariaDBUsername,
},
});
return {
fullName,
host,
username: mariaDBUsername,
password: newPassword,
};
}
+6 -3
View File
@@ -1,3 +1,6 @@
import { DsqlCrudParam } from "../../types";
import { DsqlCrudReturn } from "./crud";
export default function dsqlCrudGet({ table, query, count, countOnly, }: DsqlCrudParam<any>): Promise<DsqlCrudReturn>;
import { APIResponseObject, DsqlCrudParam } from "../../types";
export default function <T extends {
[key: string]: any;
} = {
[key: string]: any;
}>({ table, query, count, countOnly, dbFullName, }: Omit<DsqlCrudParam<T>, "action" | "data" | "sanitize">): Promise<APIResponseObject>;
+52 -62
View File
@@ -1,70 +1,60 @@
"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());
import sqlGenerator from "../../functions/dsql/sql/sql-generator";
import connDbHandler from "../db/conn-db-handler";
export default async function ({ table, query, count, countOnly, dbFullName, }) {
var _a, _b, _c, _d;
let queryObject;
queryObject = sqlGenerator({
tableName: table,
genObject: query,
dbFullName,
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = dsqlCrudGet;
const sql_generator_1 = __importDefault(require("../../functions/dsql/sql/sql-generator"));
const conn_db_handler_1 = __importDefault(require("../db/conn-db-handler"));
function dsqlCrudGet(_a) {
return __awaiter(this, arguments, void 0, function* ({ table, query, count, countOnly, }) {
var _b, _c, _d, _e;
let queryObject;
queryObject = (0, sql_generator_1.default)({
const DB_CONN = global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
let connQueries = [
{
query: queryObject === null || queryObject === void 0 ? void 0 : queryObject.string,
values: (queryObject === null || queryObject === void 0 ? void 0 : queryObject.values) || [],
},
];
const countQueryObject = count || countOnly
? sqlGenerator({
tableName: table,
genObject: query,
count: true,
dbFullName,
})
: undefined;
if (count && countQueryObject) {
connQueries.push({
query: countQueryObject.string,
values: countQueryObject.values,
});
const DB_CONN = global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
let connQueries = [
}
else if (countOnly && countQueryObject) {
connQueries = [
{
query: queryObject === null || queryObject === void 0 ? void 0 : queryObject.string,
values: (queryObject === null || queryObject === void 0 ? void 0 : queryObject.values) || [],
},
];
const countQueryObject = count || countOnly
? (0, sql_generator_1.default)({
tableName: table,
genObject: query,
count: true,
})
: undefined;
if (count && countQueryObject) {
connQueries.push({
query: countQueryObject.string,
values: countQueryObject.values,
});
}
else if (countOnly && countQueryObject) {
connQueries = [
{
query: countQueryObject.string,
values: countQueryObject.values,
},
];
}
const res = yield (0, conn_db_handler_1.default)(DB_CONN, connQueries);
const isSuccess = Array.isArray(res) && Array.isArray(res[0]);
return {
success: isSuccess,
payload: isSuccess ? (countOnly ? null : res[0]) : null,
error: isSuccess ? undefined : res === null || res === void 0 ? void 0 : res.error,
queryObject,
count: isSuccess
? ((_c = (_b = res[1]) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c["COUNT(*)"])
? res[1][0]["COUNT(*)"]
: ((_e = (_d = res[0]) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e["COUNT(*)"])
? res[0][0]["COUNT(*)"]
: undefined
: undefined,
};
});
},
];
}
const res = await connDbHandler(DB_CONN, connQueries);
const isSuccess = Array.isArray(res) && Array.isArray(res[0]);
return {
success: isSuccess,
payload: isSuccess ? (countOnly ? null : res[0]) : null,
batchPayload: isSuccess ? (countOnly ? null : res) : null,
error: isSuccess ? undefined : res === null || res === void 0 ? void 0 : res.error,
errors: res === null || res === void 0 ? void 0 : res.errors,
queryObject: {
sql: queryObject === null || queryObject === void 0 ? void 0 : queryObject.string,
params: queryObject === null || queryObject === void 0 ? void 0 : queryObject.values,
},
count: isSuccess
? ((_b = (_a = res[1]) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b["COUNT(*)"])
? res[1][0]["COUNT(*)"]
: ((_d = (_c = res[0]) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d["COUNT(*)"])
? res[0][0]["COUNT(*)"]
: undefined
: undefined,
};
}
+2 -8
View File
@@ -1,12 +1,6 @@
import sqlGenerator from "../../functions/dsql/sql/sql-generator";
import { DsqlCrudParam, PostReturn } from "../../types";
export type DsqlCrudReturn = (PostReturn & {
queryObject?: ReturnType<Awaited<typeof sqlGenerator>>;
count?: number;
batchPayload?: any[][] | null;
}) | null;
import { APIResponseObject, DsqlCrudParam } from "../../types";
export default function dsqlCrud<T extends {
[key: string]: any;
} = {
[key: string]: any;
}>(params: DsqlCrudParam<T>): Promise<DsqlCrudReturn>;
}, K extends string = string>(params: DsqlCrudParam<T, K>): Promise<APIResponseObject>;
+60 -62
View File
@@ -1,63 +1,61 @@
"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 = dsqlCrud;
const post_1 = __importDefault(require("../../actions/post"));
// import dsqlCrudBatchGet from "./crud-batch-get";
const crud_get_1 = __importDefault(require("./crud-get"));
function dsqlCrud(params) {
return __awaiter(this, void 0, void 0, function* () {
const { action, data, table, targetValue, sanitize, targetField, targetId, } = params;
const finalData = sanitize ? sanitize(data) : data;
switch (action) {
case "get":
return yield (0, crud_get_1.default)(params);
// case "batch-get":
// return await dsqlCrudBatchGet(params);
case "insert":
return yield (0, post_1.default)({
query: {
action: "insert",
table,
data: finalData,
},
forceLocal: true,
});
case "update":
data === null || data === void 0 ? true : delete data.id;
return yield (0, post_1.default)({
query: {
action: "update",
table,
identifierColumnName: targetField || "id",
identifierValue: String(targetValue || targetId),
data: finalData,
},
forceLocal: true,
});
case "delete":
return yield (0, post_1.default)({
query: {
action: "delete",
table,
identifierColumnName: targetField || "id",
identifierValue: String(targetValue || targetId),
},
forceLocal: true,
});
default:
return null;
}
});
import sqlDeleteGenerator from "../../functions/dsql/sql/sql-delete-generator";
import dsqlCrudGet from "./crud-get";
import connDbHandler from "../db/conn-db-handler";
import addDbEntry from "../../functions/backend/db/addDbEntry";
import updateDbEntry from "../../functions/backend/db/updateDbEntry";
export default async function dsqlCrud(params) {
const { action, data, table, targetValue, sanitize, targetField, targetId, dbFullName, deleteData, batchData, deleteKeyValues, } = params;
const finalData = (sanitize ? sanitize({ data }) : data);
const finalBatchData = (sanitize ? sanitize({ batchData }) : batchData);
const DB_CONN = global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
switch (action) {
case "get":
return await dsqlCrudGet(params);
// case "batch-get":
// return await dsqlCrudBatchGet(params);
case "insert":
const INSERT_RESULT = await addDbEntry({
data: finalData,
batchData: finalBatchData,
tableName: table,
dbFullName,
});
return INSERT_RESULT;
case "update":
data === null || data === void 0 ? true : delete data.id;
const UPDATE_RESULT = await updateDbEntry({
data: finalData,
tableName: table,
dbFullName,
identifierColumnName: (targetField || "id"),
identifierValue: String(targetValue || targetId),
});
return UPDATE_RESULT;
case "delete":
const deleteQuery = sqlDeleteGenerator({
data: targetId
? { id: targetId }
: targetField && targetValue
? { [targetField]: targetValue }
: deleteData,
tableName: table,
dbFullName,
deleteKeyValues,
});
const res = (await connDbHandler(DB_CONN, deleteQuery === null || deleteQuery === void 0 ? void 0 : deleteQuery.query, deleteQuery === null || deleteQuery === void 0 ? void 0 : deleteQuery.values));
return {
success: Boolean(res.affectedRows),
payload: res,
queryObject: {
sql: (deleteQuery === null || deleteQuery === void 0 ? void 0 : deleteQuery.query) || "",
params: (deleteQuery === null || deleteQuery === void 0 ? void 0 : deleteQuery.values) || [],
},
};
default:
return {
success: false,
payload: undefined,
msg: "Invalid action",
};
}
}
+142 -156
View File
@@ -1,164 +1,150 @@
"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 = dsqlMethodCrud;
const lodash_1 = __importDefault(require("lodash"));
const deserialize_query_1 = __importDefault(require("../deserialize-query"));
const ejson_1 = __importDefault(require("../ejson"));
const numberfy_1 = __importDefault(require("../numberfy"));
const crud_1 = __importDefault(require("./crud"));
function dsqlMethodCrud(_a) {
return __awaiter(this, arguments, void 0, function* ({ method, tableName, addUser, user, extraData, transformData, existingData, body, query, targetId, sanitize, transformQuery, debug, }) {
var _b, _c, _d;
let result = {
success: false,
};
try {
let finalBody = body;
let finalQuery = (0, deserialize_query_1.default)(query);
let LIMIT = 10;
let PAGE = 1;
let OFFSET = (PAGE - 1) * LIMIT;
if (method == "GET") {
const newFinalQuery = lodash_1.default.cloneDeep(finalQuery || {});
Object.keys(newFinalQuery).forEach((key) => {
const value = newFinalQuery[key];
if (typeof value == "string" && value.match(/^\{|^\[/)) {
newFinalQuery[key] = ejson_1.default.stringify(value);
}
if (value == "true") {
newFinalQuery[key] = true;
}
if (value == "false") {
newFinalQuery[key] = false;
}
});
if (newFinalQuery.limit)
LIMIT = (0, numberfy_1.default)(newFinalQuery.limit);
if (newFinalQuery.page)
PAGE = (0, numberfy_1.default)(newFinalQuery.page);
OFFSET = (PAGE - 1) * LIMIT;
finalQuery = newFinalQuery;
}
let finalData = finalBody
? Object.assign(Object.assign({}, finalBody), extraData)
: {};
if ((user === null || user === void 0 ? void 0 : user.id) && addUser) {
finalData = Object.assign(Object.assign({}, finalData), { [addUser.field]: String(user.id) });
}
if (transformData) {
if (debug) {
console.log("DEBUG:::transforming Data ...");
import _ from "lodash";
import deserializeQuery from "../deserialize-query";
import EJSON from "../ejson";
import numberfy from "../numberfy";
import dsqlCrud from "./crud";
export default async function dsqlMethodCrud({ method, tableName, addUser, user, extraData, transformData, existingData, body, query, targetId, sanitize, transformQuery, debug, }) {
var _a, _b, _c, _d, _e;
let result = {
success: false,
};
try {
let finalBody = body;
let finalQuery = deserializeQuery(query);
let LIMIT = 10;
let PAGE = 1;
let OFFSET = (PAGE - 1) * LIMIT;
if (method == "GET") {
const newFinalQuery = _.cloneDeep(finalQuery || {});
Object.keys(newFinalQuery).forEach((key) => {
const value = newFinalQuery[key];
if (typeof value == "string" && value.match(/^\{|^\[/)) {
newFinalQuery[key] = EJSON.stringify(value);
}
finalData = (yield transformData({
data: finalData,
existingData: existingData,
user,
reqMethod: method,
}));
}
if (transformQuery) {
if (debug) {
console.log("DEBUG:::transforming Query ...");
if (value == "true") {
newFinalQuery[key] = true;
}
finalQuery = yield transformQuery({
query: finalQuery || {},
user,
reqMethod: method,
});
}
if (value == "false") {
newFinalQuery[key] = false;
}
});
if (newFinalQuery.limit)
LIMIT = numberfy(newFinalQuery.limit);
if (newFinalQuery.page)
PAGE = numberfy(newFinalQuery.page);
OFFSET = (PAGE - 1) * LIMIT;
finalQuery = newFinalQuery;
}
let finalData = finalBody
? Object.assign(Object.assign({}, finalBody), extraData)
: {};
if ((user === null || user === void 0 ? void 0 : user.id) && addUser) {
finalData = Object.assign(Object.assign({}, finalData), { [addUser.field]: String(user.id) });
}
if (transformData) {
if (debug) {
console.log("DEBUG:::finalQuery", finalQuery);
console.log("DEBUG:::finalData", finalData);
console.log("DEBUG:::transforming Data ...");
}
switch (method) {
case "GET":
const GET_RESULT = yield (0, crud_1.default)({
action: "get",
table: tableName,
query: Object.assign(Object.assign({}, finalQuery), { query: Object.assign(Object.assign({}, finalQuery === null || finalQuery === void 0 ? void 0 : finalQuery.query), ((user === null || user === void 0 ? void 0 : user.id) && addUser
? {
[addUser.field]: {
value: String(user.id),
},
}
: undefined)), limit: LIMIT, offset: OFFSET }),
sanitize,
});
result = {
success: Boolean(GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.success),
payload: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.payload,
msg: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.msg,
error: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.error,
queryObject: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.queryObject,
};
break;
case "POST":
const POST_RESULT = yield (0, crud_1.default)({
action: "insert",
table: tableName,
data: finalData && ((_b = Object.keys(finalData)) === null || _b === void 0 ? void 0 : _b[0])
? finalData
: undefined,
sanitize,
});
result = {
success: Boolean(POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.success),
payload: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.payload,
msg: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.msg,
error: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.error,
};
break;
case "PUT":
const PUT_RESULT = yield (0, crud_1.default)({
action: "update",
table: tableName,
data: finalData && ((_c = Object.keys(finalData)) === null || _c === void 0 ? void 0 : _c[0])
? finalData
: undefined,
targetId,
sanitize,
});
result = {
success: Boolean(PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.success),
payload: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.payload,
msg: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.msg,
error: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.error,
};
break;
case "DELETE":
const DELETE_RESULT = yield (0, crud_1.default)({
action: "delete",
table: tableName,
targetId,
sanitize,
});
result = {
success: Boolean(DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.success),
payload: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.payload,
msg: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.msg,
error: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.error,
};
break;
default:
break;
finalData = (await transformData({
data: finalData,
existingData: existingData,
user,
reqMethod: method,
}));
}
if (transformQuery) {
if (debug) {
console.log("DEBUG:::transforming Query ...");
}
return result;
finalQuery = await transformQuery({
query: finalQuery || {},
user,
reqMethod: method,
});
}
catch (error) {
(_d = global.ERROR_CALLBACK) === null || _d === void 0 ? void 0 : _d.call(global, `Method Crud Error`, error);
return result;
if (debug) {
console.log("DEBUG:::finalQuery", finalQuery);
console.log("DEBUG:::finalData", finalData);
}
});
switch (method) {
case "GET":
const GET_RESULT = await dsqlCrud({
action: "get",
table: tableName,
query: Object.assign(Object.assign({}, finalQuery), { query: Object.assign(Object.assign({}, finalQuery === null || finalQuery === void 0 ? void 0 : finalQuery.query), ((user === null || user === void 0 ? void 0 : user.id) && addUser
? {
[addUser.field]: {
value: String(user.id),
},
}
: undefined)), limit: LIMIT, offset: OFFSET }),
sanitize,
});
result = {
success: Boolean(GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.success),
payload: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.payload,
msg: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.msg,
error: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.error,
queryObject: {
string: ((_a = GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.queryObject) === null || _a === void 0 ? void 0 : _a.sql) || "",
values: ((_b = GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.queryObject) === null || _b === void 0 ? void 0 : _b.params) || [],
},
};
break;
case "POST":
const POST_RESULT = await dsqlCrud({
action: "insert",
table: tableName,
data: finalData && ((_c = Object.keys(finalData)) === null || _c === void 0 ? void 0 : _c[0])
? finalData
: undefined,
sanitize,
});
result = {
success: Boolean(POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.success),
payload: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.payload,
msg: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.msg,
error: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.error,
};
break;
case "PUT":
const PUT_RESULT = await dsqlCrud({
action: "update",
table: tableName,
data: finalData && ((_d = Object.keys(finalData)) === null || _d === void 0 ? void 0 : _d[0])
? finalData
: undefined,
targetId,
sanitize,
});
result = {
success: Boolean(PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.success),
payload: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.payload,
msg: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.msg,
error: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.error,
};
break;
case "DELETE":
const DELETE_RESULT = await dsqlCrud({
action: "delete",
table: tableName,
targetId,
sanitize,
});
result = {
success: Boolean(DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.success),
payload: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.payload,
msg: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.msg,
error: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.error,
};
break;
default:
break;
}
return result;
}
catch (error) {
(_e = global.ERROR_CALLBACK) === null || _e === void 0 ? void 0 : _e.call(global, `Method Crud Error`, error);
return result;
}
}
+3 -1
View File
@@ -1,10 +1,12 @@
import { ServerlessMysql } from "serverless-mysql";
import { DSQLErrorObject } from "../../types";
export type ConnDBHandlerQueryObject = {
query: string;
values?: (string | number | undefined)[];
};
type Return<ReturnType = any> = ReturnType | null | {
error: string;
error?: string;
errors?: DSQLErrorObject[];
};
/**
* # Run Query From MySQL Connection
+73 -79
View File
@@ -1,25 +1,10 @@
"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 = connDbHandler;
const debug_log_1 = __importDefault(require("../logging/debug-log"));
import debugLog from "../logging/debug-log";
/**
* # Run Query From MySQL Connection
* @description Run a query from a pre-existing MySQL/Mariadb Connection
* setup with `serverless-mysql` npm module
*/
function connDbHandler(
export default async function connDbHandler(
/**
* ServerlessMySQL Connection Object
*/
@@ -32,74 +17,83 @@ query,
* Array of Values to Sanitize and Inject
*/
values, debug) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
try {
if (!conn)
throw new Error("No Connection Found!");
if (!query)
throw new Error("Query String Required!");
if (typeof query == "string") {
const res = yield conn.query(trimQuery(query), values);
if (debug) {
(0, debug_log_1.default)({
log: res,
addTime: true,
label: "res",
});
}
return JSON.parse(JSON.stringify(res));
}
else if (typeof query == "object") {
const resArray = [];
for (let i = 0; i < query.length; i++) {
try {
const queryObj = query[i];
const queryObjRes = yield conn.query(trimQuery(queryObj.query), queryObj.values);
if (debug) {
(0, debug_log_1.default)({
log: queryObjRes,
addTime: true,
label: "queryObjRes",
});
}
resArray.push(JSON.parse(JSON.stringify(queryObjRes)));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Connection DB Handler Query Error`, error);
resArray.push(null);
}
}
if (debug) {
(0, debug_log_1.default)({
log: resArray,
addTime: true,
label: "resArray",
});
}
return resArray;
}
else {
return null;
}
}
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Connection DB Handler Error`, error);
var _a, _b;
try {
if (!conn)
throw new Error("No Connection Found!");
if (!query)
throw new Error("Query String Required!");
let queryErrorArray = [];
if (typeof query == "string") {
const res = await conn.query(trimQuery(query), values);
if (debug) {
(0, debug_log_1.default)({
log: `Connection DB Handler Error: ${error.message}`,
debugLog({
log: res,
addTime: true,
label: "Error",
label: "res",
});
}
return {
error: `Connection DB Handler Error: ${error.message}`,
};
return JSON.parse(JSON.stringify(res));
}
finally {
conn === null || conn === void 0 ? void 0 : conn.end();
else if (typeof query == "object") {
const resArray = [];
for (let i = 0; i < query.length; i++) {
let currentQueryError = {};
try {
const queryObj = query[i];
currentQueryError.sql = queryObj.query;
currentQueryError.sqlValues = queryObj.values;
const queryObjRes = await conn.query(trimQuery(queryObj.query), queryObj.values);
if (debug) {
debugLog({
log: queryObjRes,
addTime: true,
label: "queryObjRes",
});
}
resArray.push(JSON.parse(JSON.stringify(queryObjRes)));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Connection DB Handler Query Error`, error);
resArray.push(null);
currentQueryError["error"] = error.message;
queryErrorArray.push(currentQueryError);
}
}
if (debug) {
debugLog({
log: resArray,
addTime: true,
label: "resArray",
});
}
if (queryErrorArray[0]) {
return {
errors: queryErrorArray,
};
}
return resArray;
}
});
else {
return null;
}
}
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Connection DB Handler Error`, error);
if (debug) {
debugLog({
log: `Connection DB Handler Error: ${error.message}`,
addTime: true,
label: "Error",
});
}
return {
error: `Connection DB Handler Error: ${error.message}`,
};
}
finally {
conn === null || conn === void 0 ? void 0 : conn.end();
}
}
function trimQuery(query) {
return query.replace(/\n/gm, "").replace(/ {2,}/g, "").trim();
@@ -0,0 +1 @@
export default function dataTypeConstructor(dataType: string, limit?: number, decimal?: number): string;
@@ -0,0 +1,20 @@
import dataTypeParser, { DataTypesWithNumbers } from "./data-type-parser";
export default function dataTypeConstructor(dataType, limit, decimal) {
let finalType = dataTypeParser(dataType).type;
if (!DataTypesWithNumbers.includes(finalType)) {
return finalType;
}
if (finalType == "VARCHAR") {
return (finalType += `(${limit || 250})`);
}
if (finalType == "DECIMAL" ||
finalType == "FLOAT" ||
finalType == "DOUBLE") {
return (finalType += `(${limit || 10},${decimal || 2})`);
}
if (limit && !decimal)
finalType += `(${limit})`;
if (limit && decimal)
finalType += `(${limit},${decimal})`;
return finalType;
}
@@ -0,0 +1,10 @@
import DataTypes from "../../../data/data-types";
export declare const DataTypesWithNumbers: (typeof DataTypes)[number]["name"][];
export declare const DataTypesWithTwoNumbers: (typeof DataTypes)[number]["name"][];
type Return = {
type: (typeof DataTypes)[number]["name"];
limit?: number;
decimal?: number;
};
export default function dataTypeParser(dataType?: string): Return;
export {};
+40
View File
@@ -0,0 +1,40 @@
import numberfy from "../../numberfy";
export const DataTypesWithNumbers = [
"DECIMAL",
"DOUBLE",
"FLOAT",
"VARCHAR",
];
export const DataTypesWithTwoNumbers = [
"DECIMAL",
"DOUBLE",
"FLOAT",
];
export default function dataTypeParser(dataType) {
if (!dataType) {
return {
type: "VARCHAR",
limit: 250,
};
}
const dataTypeArray = dataType.split("(");
const type = dataTypeArray[0];
const number = dataTypeArray[1];
if (!DataTypesWithNumbers.includes(type)) {
return {
type,
};
}
if (number === null || number === void 0 ? void 0 : number.match(/,/)) {
const numberArr = number.split(",");
return {
type,
limit: numberfy(numberArr[0]),
decimal: numberArr[1] ? numberfy(numberArr[1]) : undefined,
};
}
return {
type,
limit: number ? numberfy(number) : undefined,
};
}
@@ -0,0 +1,11 @@
import { DSQL_ChildrenDatabaseObject, DSQL_ChildrenTablesType, DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
dbs?: DSQL_DatabaseSchemaType[];
dbSchema?: DSQL_DatabaseSchemaType;
childDbSchema?: DSQL_ChildrenDatabaseObject;
childTableSchema?: DSQL_ChildrenTablesType;
dbSlug?: string;
dbFullName?: string;
};
export default function grabTargetDatabaseSchemaIndex({ dbs, dbFullName, dbSlug, dbSchema, childDbSchema, childTableSchema, }: Params): number | undefined;
export {};
@@ -0,0 +1,10 @@
export default function grabTargetDatabaseSchemaIndex({ dbs, dbFullName, dbSlug, dbSchema, childDbSchema, childTableSchema, }) {
if (!dbs)
return undefined;
const targetDbIndex = dbs.findIndex((db) => (dbSlug && dbSlug == db.dbSlug) ||
(dbFullName && dbFullName == db.dbFullName) ||
(dbSchema && dbSchema.dbSlug && dbSchema.dbSlug == db.dbSlug));
if (targetDbIndex < 0)
return undefined;
return targetDbIndex;
}
@@ -0,0 +1,9 @@
import { DSQL_ChildrenTablesType, DSQL_TableSchemaType } from "../../../types";
type Params = {
tables?: DSQL_TableSchemaType[];
tableSchema?: DSQL_TableSchemaType;
childTableSchema?: DSQL_ChildrenTablesType;
tableName?: string;
};
export default function grabTargetTableSchemaIndex({ tables, tableName, tableSchema, childTableSchema, }: Params): number | undefined;
export {};
@@ -0,0 +1,11 @@
export default function grabTargetTableSchemaIndex({ tables, tableName, tableSchema, childTableSchema, }) {
if (!tables)
return undefined;
const targetTableIndex = tables.findIndex((tbl) => (tableName && tableName == tbl.tableName) ||
(tableSchema &&
tableSchema.tableName &&
tableSchema.tableName == tbl.tableName));
if (targetTableIndex < 0)
return undefined;
return targetTableIndex;
}
@@ -0,0 +1,7 @@
import { DSQL_TableSchemaType } from "../../../types";
type Params = {
tables: DSQL_TableSchemaType[];
tableName?: string;
};
export default function grabTargetTableSchema({ tables, tableName, }: Params): DSQL_TableSchemaType | undefined;
export {};
@@ -0,0 +1,4 @@
export default function grabTargetTableSchema({ tables, tableName, }) {
const targetTable = tables.find((tbl) => tableName && tableName == tbl.tableName);
return targetTable;
}
@@ -0,0 +1,2 @@
import { DSQL_FieldSchemaType, TextFieldTypesArray } from "../../../types";
export default function grabTextFieldType(field: DSQL_FieldSchemaType, nullReturn?: boolean): (typeof TextFieldTypesArray)[number]["value"] | undefined;
@@ -0,0 +1,19 @@
export default function grabTextFieldType(field, nullReturn) {
if (field.richText)
return "richText";
if (field.json)
return "json";
if (field.yaml)
return "yaml";
if (field.html)
return "html";
if (field.css)
return "css";
if (field.javascript)
return "javascript";
if (field.shell)
return "shell";
if (nullReturn)
return undefined;
return "plain";
}
@@ -0,0 +1,7 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
currentDbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function ({ currentDbSchema, userId }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,88 @@
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
import _ from "lodash";
import uniqueByKey from "../../unique-by-key";
export default function ({ currentDbSchema, userId }) {
var _a, _b, _c;
const newCurrentDbSchema = _.cloneDeep(currentDbSchema);
if (newCurrentDbSchema.childrenDatabases) {
for (let ch = 0; ch < newCurrentDbSchema.childrenDatabases.length; ch++) {
const dbChildDb = newCurrentDbSchema.childrenDatabases[ch];
if (!dbChildDb.dbId) {
newCurrentDbSchema.childrenDatabases.splice(ch, 1, {});
continue;
}
const targetChildDatabase = grabPrimaryRequiredDbSchema({
dbId: dbChildDb.dbId,
userId,
});
/**
* Delete child database from array if said database
* doesn't exist
*/
if ((targetChildDatabase === null || targetChildDatabase === void 0 ? void 0 : targetChildDatabase.id) && targetChildDatabase.childDatabase) {
targetChildDatabase.tables = [...newCurrentDbSchema.tables];
writeUpdatedDbSchema({
dbSchema: targetChildDatabase,
userId,
});
}
else {
(_a = newCurrentDbSchema.childrenDatabases) === null || _a === void 0 ? void 0 : _a.splice(ch, 1, {});
}
}
newCurrentDbSchema.childrenDatabases =
uniqueByKey(newCurrentDbSchema.childrenDatabases.filter((db) => Boolean(db.dbId)), "dbId");
}
/**
* Handle scenario where this database is a child of another
*/
if (currentDbSchema.childDatabase && currentDbSchema.childDatabaseDbId) {
const targetParentDatabase = grabPrimaryRequiredDbSchema({
dbId: currentDbSchema.childDatabaseDbId,
userId,
});
if (!targetParentDatabase) {
return newCurrentDbSchema;
}
/**
* Delete child Database key/values from current database if
* the parent database doesn't esit
*/
if (!(targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id)) {
delete newCurrentDbSchema.childDatabase;
delete newCurrentDbSchema.childDatabaseDbId;
return newCurrentDbSchema;
}
/**
* New Child Database Object to be appended
*/
const newChildDatabaseObject = {
dbId: currentDbSchema.id,
};
/**
* Add a new Children array in the target Database if this is the
* first child to be added to said database. Else append to array
* if it exists
*/
if ((targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id) &&
!((_b = targetParentDatabase.childrenDatabases) === null || _b === void 0 ? void 0 : _b[0])) {
targetParentDatabase.childrenDatabases = [newChildDatabaseObject];
}
else if ((targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id) &&
((_c = targetParentDatabase.childrenDatabases) === null || _c === void 0 ? void 0 : _c[0])) {
const existingChildDb = targetParentDatabase.childrenDatabases.find((db) => db.dbId == currentDbSchema.id);
if (!(existingChildDb === null || existingChildDb === void 0 ? void 0 : existingChildDb.dbId)) {
targetParentDatabase.childrenDatabases.push(newChildDatabaseObject);
}
targetParentDatabase.childrenDatabases = uniqueByKey(targetParentDatabase.childrenDatabases, "dbId");
}
/**
* Update tables for child database, which is the current database
*/
if (targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id) {
newCurrentDbSchema.tables = targetParentDatabase.tables;
writeUpdatedDbSchema({ dbSchema: targetParentDatabase, userId });
}
}
return newCurrentDbSchema;
}
@@ -0,0 +1,9 @@
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../../types";
type Params = {
currentDbSchema: DSQL_DatabaseSchemaType;
currentTableSchema: DSQL_TableSchemaType;
currentTableSchemaIndex: number;
userId: string | number;
};
export default function ({ currentDbSchema, currentTableSchema, currentTableSchemaIndex, userId, }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,133 @@
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
import _ from "lodash";
import uniqueByKey from "../../unique-by-key";
export default function ({ currentDbSchema, currentTableSchema, currentTableSchemaIndex, userId, }) {
var _a, _b, _c, _d, _e, _f, _g;
if (!currentDbSchema.dbFullName) {
throw new Error(`Resolve Children tables ERROR => currentDbSchema.dbFullName not found!`);
}
const newCurrentDbSchema = _.cloneDeep(currentDbSchema);
if (newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) {
for (let ch = 0; ch <
newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables
.length; ch++) {
const childTable = newCurrentDbSchema.tables[currentTableSchemaIndex]
.childrenTables[ch];
if (!childTable.dbId || !childTable.tableId) {
(_a = newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) === null || _a === void 0 ? void 0 : _a.splice(ch, 1, {});
continue;
}
const targetChildTableParentDatabase = grabPrimaryRequiredDbSchema({
dbId: childTable.dbId,
userId,
});
/**
* Delete child table from array if the parent database
* of said child table has been deleted or doesn't exist
*/
if (!(targetChildTableParentDatabase === null || targetChildTableParentDatabase === void 0 ? void 0 : targetChildTableParentDatabase.dbFullName)) {
(_b = newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) === null || _b === void 0 ? void 0 : _b.splice(ch, 1, {});
}
else {
/**
* Delete child table from array if the parent database
* exists but the target tabled has been deleted or doesn't
* exist
*/
const targetChildTableParentDatabaseTableIndex = targetChildTableParentDatabase.tables.findIndex((tbl) => tbl.id == childTable.tableId);
const targetChildTableParentDatabaseTable = targetChildTableParentDatabase.tables[targetChildTableParentDatabaseTableIndex];
if (targetChildTableParentDatabaseTable === null || targetChildTableParentDatabaseTable === void 0 ? void 0 : targetChildTableParentDatabaseTable.childTable) {
targetChildTableParentDatabase.tables[targetChildTableParentDatabaseTableIndex].fields = [...currentTableSchema.fields];
targetChildTableParentDatabase.tables[targetChildTableParentDatabaseTableIndex].indexes = [...(currentTableSchema.indexes || [])];
writeUpdatedDbSchema({
dbSchema: targetChildTableParentDatabase,
userId,
});
}
else {
(_c = newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) === null || _c === void 0 ? void 0 : _c.splice(ch, 1, {});
}
}
}
if ((_d = newCurrentDbSchema.tables[currentTableSchemaIndex]
.childrenTables) === null || _d === void 0 ? void 0 : _d[0]) {
newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables =
uniqueByKey(newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables.filter((tbl) => Boolean(tbl.dbId) && Boolean(tbl.tableId)), "dbId");
}
else {
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childrenTables;
}
}
/**
* Handle scenario where this table is a child of another
*/
if (currentTableSchema.childTable &&
currentTableSchema.childTableDbId &&
currentTableSchema.childTableDbId) {
const targetParentDatabase = grabPrimaryRequiredDbSchema({
dbId: currentTableSchema.childTableDbId,
userId,
});
const targetParentDatabaseTableIndex = targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.tables.findIndex((tbl) => tbl.id == currentTableSchema.childTableId);
const targetParentDatabaseTable = typeof targetParentDatabaseTableIndex == "number"
? targetParentDatabaseTableIndex < 0
? undefined
: targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.tables[targetParentDatabaseTableIndex]
: undefined;
/**
* Delete child Table key/values from current database if
* the parent database doesn't esit
*/
if (!(targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.dbFullName) ||
!(targetParentDatabaseTable === null || targetParentDatabaseTable === void 0 ? void 0 : targetParentDatabaseTable.tableName)) {
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTable;
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTableDbId;
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTableId;
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTableDbId;
return newCurrentDbSchema;
}
/**
* New Child Database Table Object to be appended
*/
const newChildDatabaseTableObject = {
tableId: currentTableSchema.id,
dbId: newCurrentDbSchema.id,
};
/**
* Add a new Children array in the target table schema if this is the
* first child to be added to said table schema. Else append to array
* if it exists
*/
if (typeof targetParentDatabaseTableIndex == "number" &&
!((_e = targetParentDatabaseTable.childrenTables) === null || _e === void 0 ? void 0 : _e[0])) {
targetParentDatabase.tables[targetParentDatabaseTableIndex].childrenTables = [newChildDatabaseTableObject];
}
else if (typeof targetParentDatabaseTableIndex == "number" &&
((_f = targetParentDatabaseTable.childrenTables) === null || _f === void 0 ? void 0 : _f[0])) {
const existingChildDbTable = targetParentDatabaseTable.childrenTables.find((tbl) => tbl.dbId == newCurrentDbSchema.id &&
tbl.tableId == currentTableSchema.id);
if (!(existingChildDbTable === null || existingChildDbTable === void 0 ? void 0 : existingChildDbTable.tableId)) {
(_g = targetParentDatabase.tables[targetParentDatabaseTableIndex].childrenTables) === null || _g === void 0 ? void 0 : _g.push(newChildDatabaseTableObject);
}
targetParentDatabase.tables[targetParentDatabaseTableIndex].childrenTables = uniqueByKey(targetParentDatabase.tables[targetParentDatabaseTableIndex]
.childrenTables || [], ["dbId", "tableId"]);
}
/**
* Update fields and indexes for child table, which is the
* current table
*/
if (targetParentDatabaseTable === null || targetParentDatabaseTable === void 0 ? void 0 : targetParentDatabaseTable.tableName) {
newCurrentDbSchema.tables[currentTableSchemaIndex].fields =
targetParentDatabaseTable.fields;
newCurrentDbSchema.tables[currentTableSchemaIndex].indexes =
targetParentDatabaseTable.indexes;
writeUpdatedDbSchema({ dbSchema: targetParentDatabase, userId });
}
}
return newCurrentDbSchema;
}
@@ -0,0 +1,7 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
dbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function resolveSchemaChildren({ dbSchema, userId }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,20 @@
import _ from "lodash";
import resolveSchemaChildrenHandleChildrenDatabases from "./resolve-schema-children-handle-children-databases";
import resolveSchemaChildrenHandleChildrenTables from "./resolve-schema-children-handle-children-tables";
export default function resolveSchemaChildren({ dbSchema, userId }) {
let newDbSchema = _.cloneDeep(dbSchema);
newDbSchema = resolveSchemaChildrenHandleChildrenDatabases({
currentDbSchema: newDbSchema,
userId,
});
for (let t = 0; t < newDbSchema.tables.length; t++) {
const tableSchema = newDbSchema.tables[t];
newDbSchema = resolveSchemaChildrenHandleChildrenTables({
currentDbSchema: newDbSchema,
currentTableSchema: tableSchema,
currentTableSchemaIndex: t,
userId,
});
}
return newDbSchema;
}
@@ -0,0 +1,7 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
dbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function resolveSchemaForeignKeys({ dbSchema, userId }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,27 @@
import _ from "lodash";
export default function resolveSchemaForeignKeys({ dbSchema, userId }) {
var _a;
let newDbSchema = _.cloneDeep(dbSchema);
for (let t = 0; t < newDbSchema.tables.length; t++) {
const tableSchema = newDbSchema.tables[t];
for (let f = 0; f < tableSchema.fields.length; f++) {
const fieldSchema = tableSchema.fields[f];
if ((_a = fieldSchema.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableColumnName) {
const fkDestinationTableIndex = newDbSchema.tables.findIndex((tbl) => {
var _a;
return tbl.tableName ==
((_a = fieldSchema.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableName);
});
/**
* Delete current Foreign Key if related table doesn't exist
* or has been deleted
*/
if (fkDestinationTableIndex < 0) {
delete newDbSchema.tables[t].fields[f].foreignKey;
continue;
}
}
}
}
return newDbSchema;
}
@@ -0,0 +1,10 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
userId: string | number;
dbId?: string | number;
};
export default function resolveUsersSchemaIDs({ userId, dbId }: Params): false | undefined;
export declare function resolveUserDatabaseSchemaIDs({ dbSchema, }: {
dbSchema: DSQL_DatabaseSchemaType;
}): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,54 @@
import fs from "fs";
import grabDirNames from "../../backend/names/grab-dir-names";
import _n from "../../numberfy";
import path from "path";
import _ from "lodash";
import EJSON from "../../ejson";
import { writeUpdatedDbSchema } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
export default function resolveUsersSchemaIDs({ userId, dbId }) {
const { targetUserPrivateDir, tempDirName } = grabDirNames({ userId });
if (!targetUserPrivateDir)
return false;
const schemaDirFilesFolders = fs.readdirSync(targetUserPrivateDir);
for (let i = 0; i < schemaDirFilesFolders.length; i++) {
const fileOrFolderName = schemaDirFilesFolders[i];
if (!fileOrFolderName.match(/^\d+.json/))
continue;
const fileDbId = _n(fileOrFolderName.split(".").shift());
if (!fileDbId)
continue;
if (dbId && _n(dbId) !== fileDbId) {
continue;
}
const schemaFullPath = path.join(targetUserPrivateDir, fileOrFolderName);
if (!fs.existsSync(schemaFullPath))
continue;
const dbSchema = EJSON.parse(fs.readFileSync(schemaFullPath, "utf-8"));
if (!dbSchema)
continue;
let newDbSchema = resolveUserDatabaseSchemaIDs({ dbSchema });
writeUpdatedDbSchema({ dbSchema: newDbSchema, userId });
}
}
export function resolveUserDatabaseSchemaIDs({ dbSchema, }) {
let newDbSchema = _.cloneDeep(dbSchema);
if (!newDbSchema.id)
newDbSchema.id = dbSchema.id;
newDbSchema.tables.forEach((tbl, index) => {
var _a;
if (!tbl.id) {
newDbSchema.tables[index].id = index + 1;
}
tbl.fields.forEach((fld, flIndx) => {
if (!fld.id) {
newDbSchema.tables[index].fields[flIndx].id = flIndx + 1;
}
});
(_a = tbl.indexes) === null || _a === void 0 ? void 0 : _a.forEach((indx, indIndx) => {
if (!indx.id && newDbSchema.tables[index].indexes) {
newDbSchema.tables[index].indexes[indIndx].id = indIndx + 1;
}
});
});
return newDbSchema;
}
@@ -0,0 +1,2 @@
import { DSQL_FieldSchemaType, TextFieldTypesArray } from "../../../types";
export default function setTextFieldType(field: DSQL_FieldSchemaType, type?: (typeof TextFieldTypesArray)[number]["value"]): DSQL_FieldSchemaType;
@@ -0,0 +1,30 @@
import _ from "lodash";
export default function setTextFieldType(field, type) {
const newField = _.cloneDeep(field);
delete newField.css;
delete newField.richText;
delete newField.json;
delete newField.shell;
delete newField.html;
delete newField.javascript;
delete newField.yaml;
delete newField.code;
delete newField.defaultValueLiteral;
if (type == "css")
return Object.assign(Object.assign({}, newField), { css: true });
if (type == "richText")
return Object.assign(Object.assign({}, newField), { richText: true });
if (type == "json")
return Object.assign(Object.assign({}, newField), { json: true });
if (type == "shell")
return Object.assign(Object.assign({}, newField), { shell: true });
if (type == "html")
return Object.assign(Object.assign({}, newField), { html: true });
if (type == "yaml")
return Object.assign(Object.assign({}, newField), { yaml: true });
if (type == "javascript")
return Object.assign(Object.assign({}, newField), { javascript: true });
if (type == "code")
return Object.assign(Object.assign({}, newField), { code: true });
return Object.assign({}, newField);
}
+6
View File
@@ -0,0 +1,6 @@
/**
* # Delete all matches in an Array
*/
export default function deleteByKey<T extends {
[k: string]: any;
} = any>(arr: T[], key: keyof T | (keyof T)[]): T[];
+29
View File
@@ -0,0 +1,29 @@
import _ from "lodash";
/**
* # Delete all matches in an Array
*/
export default function deleteByKey(arr, key) {
let newArray = _.cloneDeep(arr);
for (let i = 0; i < newArray.length; i++) {
const item = newArray[i];
if (Array.isArray(key)) {
const targetMatches = [];
for (let k = 0; k < key.length; k++) {
const ky = key[k];
const targetValue = item[ky];
const targetOriginValue = item[ky];
targetMatches.push(targetValue == targetOriginValue);
}
if (!targetMatches.find((mtch) => !mtch)) {
newArray.splice(i, 1);
}
}
else {
let existingValue = newArray.find((v) => v[key] == item[key]);
if (existingValue) {
newArray.splice(i, 1);
}
}
}
return newArray;
}
+4 -10
View File
@@ -1,22 +1,16 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = deserializeQuery;
const ejson_1 = __importDefault(require("./ejson"));
import EJSON from "./ejson";
/**
* # Convert Serialized Query back to object
*/
function deserializeQuery(query) {
let queryObject = typeof query == "object" ? query : Object(ejson_1.default.parse(query));
export default function deserializeQuery(query) {
let queryObject = typeof query == "object" ? query : Object(EJSON.parse(query));
const keys = Object.keys(queryObject);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = queryObject[key];
if (typeof value == "string") {
if (value.match(/^\{|^\[/)) {
queryObject[key] = ejson_1.default.parse(value);
queryObject[key] = EJSON.parse(value);
}
}
}
+1 -3
View File
@@ -1,5 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* # EJSON parse string
*/
@@ -32,4 +30,4 @@ const EJSON = {
parse,
stringify,
};
exports.default = EJSON;
export default EJSON;
+7 -13
View File
@@ -1,23 +1,17 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = emptyDirectory;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
function emptyDirectory(dir) {
import fs from "fs";
import path from "path";
export default function emptyDirectory(dir) {
try {
const dirContent = fs_1.default.readdirSync(dir);
const dirContent = fs.readdirSync(dir);
for (let i = 0; i < dirContent.length; i++) {
const fileFolder = dirContent[i];
const fullFileFolderPath = path_1.default.join(dir, fileFolder);
const stat = fs_1.default.statSync(fullFileFolderPath);
const fullFileFolderPath = path.join(dir, fileFolder);
const stat = fs.statSync(fullFileFolderPath);
if (stat.isDirectory()) {
emptyDirectory(fullFileFolderPath);
continue;
}
fs_1.default.unlinkSync(fullFileFolderPath);
fs.unlinkSync(fullFileFolderPath);
}
}
catch (error) {
+1 -3
View File
@@ -1,5 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* # End MYSQL Connection
*/
@@ -10,4 +8,4 @@ function endConnection(connection) {
});
}
}
exports.default = endConnection;
export default endConnection;
+1
View File
@@ -0,0 +1 @@
export default function envsub(str: string): string;
+6
View File
@@ -0,0 +1,6 @@
export default function envsub(str) {
return str.replace(/\$([A-Z_]+)|\${([A-Z_]+)}/g, (match, var1, var2) => {
const varName = var1 || var2;
return process.env[varName] || match;
});
}
+1 -4
View File
@@ -1,7 +1,4 @@
"use strict";
// @ts-check
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = generateColumnDescription;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
@@ -11,7 +8,7 @@ exports.default = generateColumnDescription;
/**
* # Generate SQL text for Field
*/
function generateColumnDescription({ columnData, primaryKeySet, }) {
export default function generateColumnDescription({ columnData, primaryKeySet, }) {
/**
* Format tableInfoArray
*
+7
View File
@@ -0,0 +1,7 @@
declare const APIParadigms: readonly ["crud", "media", "schema"];
type Params = {
version?: string;
paradigm?: (typeof APIParadigms)[number];
};
export default function grabAPIBasePath({ version, paradigm }: Params): string;
export {};
+8
View File
@@ -0,0 +1,8 @@
const APIParadigms = ["crud", "media", "schema"];
export default function grabAPIBasePath({ version, paradigm }) {
let basePath = `/api/v${version || "1"}`;
if (paradigm) {
basePath += `/${paradigm}`;
}
return basePath;
}
@@ -0,0 +1,2 @@
import { DSQL_DatabaseSchemaType } from "../types";
export default function grabAppMainDbSchema(): DSQL_DatabaseSchemaType | undefined;
+11
View File
@@ -0,0 +1,11 @@
import fs from "fs";
import grabDirNames from "./backend/names/grab-dir-names";
import EJSON from "./ejson";
export default function grabAppMainDbSchema() {
const { appSchemaJSONFile } = grabDirNames();
if (!fs.existsSync(appSchemaJSONFile)) {
return undefined;
}
const parsedAppSchema = EJSON.parse(fs.readFileSync(appSchemaJSONFile, "utf-8"));
return parsedAppSchema;
}
+2
View File
@@ -0,0 +1,2 @@
import { AppVersions } from "../types";
export default function grabAppVersion(): (typeof AppVersions)[number];
+11
View File
@@ -0,0 +1,11 @@
import { AppVersions } from "../types";
export default function grabAppVersion() {
const appVersionEnv = process.env.NEXT_PUBLIC_VERSION;
const finalAppVersion = (appVersionEnv ||
"community");
const targetAppVersion = AppVersions.find((version) => version.value === finalAppVersion);
if (!targetAppVersion) {
throw new Error(`Invalid App Version: ${finalAppVersion}`);
}
return targetAppVersion;
}
+3 -9
View File
@@ -1,15 +1,9 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabCookieExpiryDate;
const numberfy_1 = __importDefault(require("./numberfy"));
function grabCookieExpiryDate() {
import numberfy from "./numberfy";
export default function grabCookieExpiryDate() {
const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
const ONE_WEEK_IN_SECONDS = ONE_DAY_IN_SECONDS * 7;
const COOKIE_EXPIRY_TIME_IN_SECONDS = process.env.DSQL_SESSION_EXPIRY_TIME
? (0, numberfy_1.default)(process.env.DSQL_SESSION_EXPIRY_TIME)
? numberfy(process.env.DSQL_SESSION_EXPIRY_TIME)
: ONE_WEEK_IN_SECONDS;
const COOKIE_EXPIRY_IN_MILLISECONDS = COOKIE_EXPIRY_TIME_IN_SECONDS * 1000;
const COOKIE_EXPIRY_DATE = new Date(Date.now() + COOKIE_EXPIRY_IN_MILLISECONDS).toUTCString();
+10 -2
View File
@@ -1,9 +1,17 @@
import { UserType } from "../types";
type Param = {
/**
* Database full name or slug
*/
dbName?: string;
userId?: string | number;
user?: UserType | null;
};
/**
* # Grab Database Full Name
* # Grab full database name
* @description Grab full database name from slug or full name
* @param param0
* @returns
*/
export default function grabDbFullName({ dbName, userId }: Param): string;
export default function grabDbFullName({ dbName, userId, user, }: Param): string | undefined;
export {};
+17 -13
View File
@@ -1,16 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabDbFullName;
import slugify from "./slugify";
/**
* # Grab Database Full Name
* # Grab full database name
* @description Grab full database name from slug or full name
* @param param0
* @returns
*/
function grabDbFullName({ dbName, userId }) {
if (!dbName)
throw new Error(`Database name not provided to db name parser funciton`);
const sanitizedName = dbName.replace(/[^a-z0-9\_]/g, "");
const cleanedDbName = sanitizedName.replace(/datasquirel_user_\d+_/, "");
if (!userId)
return cleanedDbName;
const dbNamePrefix = `datasquirel_user_${userId}_`;
return dbNamePrefix + cleanedDbName;
export default function grabDbFullName({ dbName, userId, user, }) {
const finalUserId = (user === null || user === void 0 ? void 0 : user.id) || userId;
if (!finalUserId) {
return dbName;
}
if (!dbName) {
return;
}
const dbNamePrefix = process.env.DSQL_USER_DB_PREFIX;
const parsedDbName = slugify(dbName, "_");
const dbSlug = parsedDbName.replace(new RegExp(`${dbNamePrefix}_?\\d+_`), "");
return slugify(`${dbNamePrefix}_${finalUserId}_${dbSlug}`, "_");
}
+21
View File
@@ -0,0 +1,21 @@
import { UserType } from "../types";
type Param = {
/**
* Database full name or slug
*/
dbName?: string;
userId?: string | number;
user?: UserType | null;
};
/**
* # Grab full database name
* @description Grab full database name from slug or full name
* @param param0
* @returns
*/
export default function grabDbNames({ dbName, userId, user }: Param): {
userDbPrefix: string;
dbFullName: string | undefined;
dbNamePrefix: string | undefined;
};
export {};
+14
View File
@@ -0,0 +1,14 @@
import grabDbFullName from "./grab-db-full-name";
/**
* # Grab full database name
* @description Grab full database name from slug or full name
* @param param0
* @returns
*/
export default function grabDbNames({ dbName, userId, user }) {
const dbNamePrefix = process.env.DSQL_USER_DB_PREFIX;
const finalUserId = (user === null || user === void 0 ? void 0 : user.id) || userId;
const userDbPrefix = `${dbNamePrefix}${finalUserId}_`;
const dbFullName = grabDbFullName({ dbName, user, userId });
return { userDbPrefix, dbFullName, dbNamePrefix };
}
@@ -0,0 +1,13 @@
export default function grabDockerResourceIPNumbers(): {
readonly db: 32;
readonly maxscale: 24;
readonly postDbSetup: 43;
readonly reverse_proxy: 34;
readonly web: 35;
readonly websocket: 36;
readonly cron: 27;
readonly db_cron: 20;
readonly replica_1: 37;
readonly replica_2: 38;
readonly web_app_post_db_setup: 71;
};
@@ -0,0 +1,15 @@
export default function grabDockerResourceIPNumbers() {
return {
db: 32,
maxscale: 24,
postDbSetup: 43,
reverse_proxy: 34,
web: 35,
websocket: 36,
cron: 27,
db_cron: 20,
replica_1: 37,
replica_2: 38,
web_app_post_db_setup: 71,
};
}
+6 -12
View File
@@ -1,17 +1,11 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabDSQLConnection;
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
import mysql from "serverless-mysql";
/**
* # Grab General CONNECTION for DSQL
*/
function grabDSQLConnection(param) {
export default function grabDSQLConnection(param) {
if (global.DSQL_USE_LOCAL || (param === null || param === void 0 ? void 0 : param.local)) {
return (global.DSQL_DB_CONN ||
(0, serverless_mysql_1.default)({
mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
@@ -28,7 +22,7 @@ function grabDSQLConnection(param) {
}
if (param === null || param === void 0 ? void 0 : param.ro) {
return (global.DSQL_READ_ONLY_DB_CONN ||
(0, serverless_mysql_1.default)({
mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_READ_ONLY_USERNAME,
@@ -42,7 +36,7 @@ function grabDSQLConnection(param) {
}
if (param === null || param === void 0 ? void 0 : param.fa) {
return (global.DSQL_FULL_ACCESS_DB_CONN ||
(0, serverless_mysql_1.default)({
mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_FULL_ACCESS_USERNAME,
@@ -55,7 +49,7 @@ function grabDSQLConnection(param) {
}));
}
return (global.DSQL_DB_CONN ||
(0, serverless_mysql_1.default)({
mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
+4 -10
View File
@@ -1,16 +1,10 @@
"use strict";
// @ts-check
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabHostNames;
const https_1 = __importDefault(require("https"));
const http_1 = __importDefault(require("http"));
import https from "https";
import http from "http";
/**
* # Grab Names For Query
*/
function grabHostNames(param) {
export default function grabHostNames(param) {
var _a, _b;
const finalEnv = (param === null || param === void 0 ? void 0 : param.env)
? Object.assign(Object.assign({}, process.env), param.env) : process.env;
@@ -30,7 +24,7 @@ function grabHostNames(param) {
return {
host: remoteHost || localHost || "datasquirel.com",
port: remoteHostPort || localHostPort || 443,
scheme: (scheme === null || scheme === void 0 ? void 0 : scheme.match(/^http$/i)) ? http_1.default : https_1.default,
scheme: (scheme === null || scheme === void 0 ? void 0 : scheme.match(/^http$/i)) ? http : https,
user_id: (param === null || param === void 0 ? void 0 : param.userId) || String(finalEnv["DSQL_API_USER_ID"] || 0),
};
}
@@ -0,0 +1 @@
export default function grabInstanceGlobalNetWorkName(): string;
@@ -0,0 +1,4 @@
export default function grabInstanceGlobalNetWorkName() {
const deploymentName = process.env.DSQL_DEPLOYMENT_NAME || "dsql";
return `${deploymentName}_dsql_global_network`;
}
+3 -9
View File
@@ -1,15 +1,9 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = grabKeys;
const numberfy_1 = __importDefault(require("./numberfy"));
import numberfy from "./numberfy";
/**
* # Grab Encryption Keys
* @description Grab Required Encryption Keys
*/
function grabKeys(param) {
export default function grabKeys(param) {
return {
key: (param === null || param === void 0 ? void 0 : param.encryptionKey) || process.env.DSQL_ENCRYPTION_PASSWORD,
keyLen: process.env.DSQL_ENCRYPTION_KEY_LENGTH
@@ -22,7 +16,7 @@ function grabKeys(param) {
"aes-192-cbc",
bufferAllocSize: (param === null || param === void 0 ? void 0 : param.bufferAllocSize) ||
(process.env.DSQL_ENCRYPTION_BUFFER_ALLOCATION_SIZE
? (0, numberfy_1.default)(process.env.DSQL_ENCRYPTION_BUFFER_ALLOCATION_SIZE)
? numberfy(process.env.DSQL_ENCRYPTION_BUFFER_ALLOCATION_SIZE)
: undefined) ||
16,
};
+3 -9
View File
@@ -1,14 +1,8 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = apiGetGrabQueryAndValues;
const sql_generator_1 = __importDefault(require("../functions/dsql/sql/sql-generator"));
function apiGetGrabQueryAndValues({ query, values }) {
import sqlGenerator from "../functions/dsql/sql/sql-generator";
export default function apiGetGrabQueryAndValues({ query, values }) {
const queryGenObject = typeof query == "string"
? undefined
: (0, sql_generator_1.default)({
: sqlGenerator({
tableName: query.table,
genObject: query.query,
dbFullName: query.dbFullName || "__db",
+11
View File
@@ -0,0 +1,11 @@
type Param = {
type: "foreign_key" | "index" | "user";
userId?: string | number;
addDate?: boolean;
};
/**
* # Grab Key Names
* @description Grab key names for foreign keys and indexes
*/
export default function grabSQLKeyName({ type, userId, addDate }: Param): string;
export {};
+23
View File
@@ -0,0 +1,23 @@
/**
* # Grab Key Names
* @description Grab key names for foreign keys and indexes
*/
export default function grabSQLKeyName({ type, userId, addDate }) {
let prefixParadigm = (() => {
if (type == "foreign_key")
return "fk";
if (type == "index")
return "indx";
if (type == "user")
return "user";
return null;
})();
let key = `dsql`;
if (prefixParadigm)
key += `_${prefixParadigm}`;
if (userId)
key += `_${userId}`;
if (addDate)
key += `_${Date.now()}`;
return key;
}
@@ -0,0 +1 @@
export default function grabSQLUserNameForUser(userId?: string | number): string;
@@ -0,0 +1,3 @@
export default function grabSQLUserNameForUser(userId) {
return `dsql_user_${userId || 0}`;
}
+12
View File
@@ -0,0 +1,12 @@
import { UserType } from "../types";
type Params = {
user?: UserType | null;
name?: string;
};
type Return = {
sqlUsername?: string;
name?: string;
nameWithoutPrefix?: string;
};
export default function grabSQLUserName({ user, name: passedName, }: Params): Return;
export {};
+22
View File
@@ -0,0 +1,22 @@
import grabSQLUserNameForUser from "./grab-sql-user-name-for-user";
export default function grabSQLUserName({ user, name: passedName, }) {
if (!user) {
console.log("No User Found");
return {};
}
const sqlUsername = grabSQLUserNameForUser(user.id);
const parsedPassedName = passedName
? passedName.replace(sqlUsername, "").replace(/^_+|_+$/, "")
: undefined;
const name = parsedPassedName
? `${sqlUsername}_${parsedPassedName}`
: undefined;
if (user.isSuperUser) {
return {
sqlUsername: undefined,
name: passedName,
nameWithoutPrefix: passedName,
};
}
return { sqlUsername, name, nameWithoutPrefix: parsedPassedName };
}
@@ -0,0 +1,14 @@
import { UserType } from "../types";
type Params = {
user?: UserType | null;
HOST?: string;
username?: string;
};
export default function grabUserMainSqlUserName({ HOST, user, username, }: Params): {
username: string;
host: string;
webHost: string;
fullName: string;
sqlUsername: string;
};
export {};
@@ -0,0 +1,16 @@
import grabSQLUserNameForUser from "./grab-sql-user-name-for-user";
import grabIPAddresses from "../utils/backend/names/grab-ip-addresses";
export default function grabUserMainSqlUserName({ HOST, user, username, }) {
const sqlUsername = grabSQLUserNameForUser(user === null || user === void 0 ? void 0 : user.id);
const { webAppIP, maxScaleIP } = grabIPAddresses();
const finalUsername = username || sqlUsername;
const finalHost = HOST || maxScaleIP || "127.0.0.1";
const fullName = `${finalUsername}@${webAppIP}`;
return {
username: finalUsername,
host: finalHost,
webHost: webAppIP,
fullName,
sqlUsername,
};
}
+9 -12
View File
@@ -1,20 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = debugLog;
const console_colors_1 = require("../console-colors");
import { ccol } from "../console-colors";
const LogTypes = ["error", "warning"];
function debugLog({ log, label, title, type, addTime }) {
export default function debugLog({ log, label, title, type, addTime }) {
const logType = (() => {
switch (type) {
case "error":
return console_colors_1.ccol.FgRed;
return ccol.FgRed;
case "warning":
return console_colors_1.ccol.FgYellow;
return ccol.FgYellow;
default:
return console_colors_1.ccol.FgGreen;
return ccol.FgGreen;
}
})();
let logTxt = `${logType}DEBUG${console_colors_1.ccol.Reset}:::`;
let logTxt = `${logType}DEBUG${ccol.Reset}:::`;
const date = new Date();
const time = date.toLocaleTimeString("en-US", {
hour: "numeric",
@@ -24,10 +21,10 @@ function debugLog({ log, label, title, type, addTime }) {
});
const logTime = `${date.toLocaleDateString()}][${time}`;
if (addTime)
logTxt = `${console_colors_1.ccol.BgWhite}[${logTime}]${console_colors_1.ccol.Reset} ` + logTxt;
logTxt = `${ccol.BgWhite}[${logTime}]${ccol.Reset} ` + logTxt;
if (title)
logTxt += `${console_colors_1.ccol.FgBlue}${title}${console_colors_1.ccol.Reset}::`;
logTxt += `${ccol.FgBlue}${title}${ccol.Reset}::`;
if (label)
logTxt += `${console_colors_1.ccol.FgWhite}${console_colors_1.ccol.Bright}${label}${console_colors_1.ccol.Reset} =>`;
logTxt += `${ccol.FgWhite}${ccol.Bright}${label}${ccol.Reset} =>`;
console.log(logTxt, log);
}
+1
View File
@@ -0,0 +1 @@
export default function normalizeText(txt: string): string;
+6
View File
@@ -0,0 +1,6 @@
export default function normalizeText(txt) {
return txt
.replace(/\n|\r|\n\r/g, " ")
.replace(/ {2,}/g, " ")
.trim();
}
+1 -4
View File
@@ -1,6 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = numberfy;
/**
* # Get Number from any input
* @example
@@ -10,7 +7,7 @@ exports.default = numberfy;
* numberfy("123.456", 0) // 123
* numberfy("123.456", 3) // 123.456
*/
function numberfy(num, decimals) {
export default function numberfy(num, decimals) {
var _a;
try {
const numberString = String(num)

Some files were not shown because too many files have changed in this diff Show More