import serverError from "./serverError"; import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER"; import addDbEntry from "./db/addDbEntry"; import createDbFromSchema from "../../shell/createDbFromSchema"; import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER"; import grabNewUsersTableSchema from "./grabNewUsersTableSchema"; import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../shell/createDbFromSchema/grab-required-database-schemas"; /** * # Add User Table to Database */ export default async function addUsersTableToDb({ userId, database, payload, dbId, }) { try { const dbFullName = database; const userPreset = grabNewUsersTableSchema({ payload }); if (!userPreset) throw new Error("Couldn't Get User Preset!"); let targetDatabase = grabPrimaryRequiredDbSchema({ dbId, userId, }); if (!targetDatabase) { throw new Error("Couldn't Find Target Database!"); } let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users"); if (typeof existingTableIndex == "number" && existingTableIndex > 0) { targetDatabase.tables[existingTableIndex] = userPreset; } else { targetDatabase.tables.push(userPreset); } writeUpdatedDbSchema({ dbSchema: targetDatabase, userId }); const targetDb = global.DSQL_USE_LOCAL ? await LOCAL_DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]) : await DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]); if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) { const newTableEntry = await addDbEntry({ dbFullName: "datasquirel", tableName: "user_database_tables", data: { user_id: userId, db_id: targetDb[0].id, db_slug: targetDatabase.dbSlug, table_name: "Users", table_slug: "users", }, }); } const dbShellUpdate = await createDbFromSchema({ userId, targetDatabase: dbFullName, }); return `Done!`; } catch ( /** @type {any} */error) { console.log(`addUsersTableToDb.ts ERROR: ${error.message}`); serverError({ component: "addUsersTableToDb", message: error.message, user: { id: userId }, }); return error.message; } }