From 0a45ddcd3773f8d6c671e0ba227d0551c1eba501 Mon Sep 17 00:00:00 2001 From: Josh Moore Date: Sun, 16 Jul 2023 20:45:25 -0600 Subject: [PATCH] feat: implement SQL mode switch --- backend/data.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/backend/data.ts b/backend/data.ts index 36505f8..730f0bd 100644 --- a/backend/data.ts +++ b/backend/data.ts @@ -3,6 +3,7 @@ import { path } from '@tycrek/joint'; import { nanoid } from 'nanoid'; import { log } from './log'; import { AssFile, AssUser, NID, FilesSchema, UsersSchema } from 'ass'; +import { UserConfig } from './UserConfig'; /** * Switcher type for exported functions @@ -17,6 +18,11 @@ const PATHS = { users: path.join('.ass-data/users.json') }; +const bothWriter = async (files: FilesSchema, users: UsersSchema) => { + await fs.writeJson(PATHS.files, files, { spaces: '\t' }); + await fs.writeJson(PATHS.users, users, { spaces: '\t' }); +}; + /** * Creates a JSON file with a given empty data template */ @@ -65,3 +71,33 @@ export const ensureFiles = (): Promise => new Promise(async (resolve, reje reject(err); } }); + +export const setDataModeToSql = (): Promise => new Promise(async (resolve, reject) => { + log.debug('Setting data mode to SQL'); + + // Main config check + if (!UserConfig.ready || !UserConfig.config.sql?.mySql) return reject(new Error('MySQL not configured')); + const mySqlConf = UserConfig.config.sql.mySql; + + // Read data files + const [files, users]: [FilesSchema, UsersSchema] = await Promise.all([fs.readJson(PATHS.files), fs.readJson(PATHS.users)]); + + // Check the MySQL configuration + const checker = (val: string) => val != null && val !== ''; + const issue = + !checker(mySqlConf.host) ? 'Missing MySQL Host' + : !checker(mySqlConf.user) ? 'Missing MySQL User' + : !checker(mySqlConf.password) ? 'Missing MySQL Password' + : !checker(mySqlConf.database) ? 'Missing MySQL Database' + + // ! Blame VS Code for this weird indentation + : undefined; + + // Set the vars + files.useSql = issue == null; + users.useSql = issue == null; + + // Write data & return + await bothWriter(files, users); + (issue) ? reject(new Error(issue)) : resolve(void 0); +});