Browse Source

Feat: Improve Database Handling (#1383)

pull/1618/head
Bernd Storath 7 months ago
committed by Bernd Storath
parent
commit
f529a41241
  1. 5
      src/server/middleware/session.ts
  2. 18
      src/server/utils/Database.ts
  3. 32
      src/server/utils/WireGuard.ts
  4. 1
      src/server/utils/session.ts
  5. 50
      src/services/database/lowdb.ts
  6. 4
      src/services/database/repositories/database.ts

5
src/server/middleware/session.ts

@ -11,11 +11,6 @@ export default defineEventHandler(async (event) => {
return; return;
} }
const system = await Database.system.get(); const system = await Database.system.get();
if (!system)
throw createError({
statusCode: 500,
statusMessage: 'Invalid',
});
const session = await getSession(event, system.sessionConfig); const session = await getSession(event, system.sessionConfig);
if (session.id && session.data.authenticated) { if (session.id && session.data.authenticated) {

18
src/server/utils/Database.ts

@ -5,11 +5,21 @@
import LowDb from '~~/services/database/lowdb'; import LowDb from '~~/services/database/lowdb';
const provider = new LowDb(); const nullObject = new Proxy(
{},
{
get() {
throw new Error('Database not yet initialized');
},
}
);
provider.connect().catch((err) => { // eslint-disable-next-line import/no-mutable-exports
console.error(err); let provider = nullObject as never as LowDb;
process.exit(1);
LowDb.connect().then((v) => {
provider = v;
WireGuard.Startup();
}); });
// TODO: check if old config exists and tell user about migration path // TODO: check if old config exists and tell user about migration path

32
src/server/utils/WireGuard.ts

@ -28,17 +28,17 @@ class WireGuard {
result.push(wg.generateServerPeer(client)); result.push(wg.generateServerPeer(client));
} }
DEBUG('Config saving...'); DEBUG('Saving Config...');
await fs.writeFile('/etc/wireguard/wg0.conf', result.join('\n\n'), { await fs.writeFile('/etc/wireguard/wg0.conf', result.join('\n\n'), {
mode: 0o600, mode: 0o600,
}); });
DEBUG('Config saved.'); DEBUG('Config saved successfully.');
} }
async #syncWireguardConfig() { async #syncWireguardConfig() {
DEBUG('Config syncing...'); DEBUG('Syncing Config...');
await wg.sync(); await wg.sync();
DEBUG('Config synced.'); DEBUG('Config synced successfully.');
} }
async getClients() { async getClients() {
@ -275,16 +275,7 @@ class WireGuard {
} }
async Startup() { async Startup() {
// TODO: improve this DEBUG('Starting Wireguard...');
await new Promise((res) => {
function wait() {
if (Database.connected) {
return res(true);
}
}
setTimeout(wait, 1000);
});
DEBUG('Starting Wireguard');
await this.#saveWireguardConfig(); await this.#saveWireguardConfig();
await wg.down().catch(() => {}); await wg.down().catch(() => {});
await wg.up().catch((err) => { await wg.up().catch((err) => {
@ -301,10 +292,11 @@ class WireGuard {
throw err; throw err;
}); });
await this.#syncWireguardConfig(); await this.#syncWireguardConfig();
DEBUG('Wireguard started successfully'); DEBUG('Wireguard started successfully.');
DEBUG('Starting Cron Job'); DEBUG('Starting Cron Job.');
await this.startCronJob(); await this.startCronJob();
DEBUG('Cron Job started successfully.');
} }
async startCronJob() { async startCronJob() {
@ -426,10 +418,4 @@ class WireGuard {
} }
} }
const inst = new WireGuard(); export default new WireGuard();
inst.Startup().catch((v) => {
console.error(v);
process.exit(1);
});
export default inst;

1
src/server/utils/session.ts

@ -6,6 +6,5 @@ export type WGSession = {
export async function useWGSession(event: H3Event) { export async function useWGSession(event: H3Event) {
const system = await Database.system.get(); const system = await Database.system.get();
if (!system) throw new Error('Invalid');
return useSession<Partial<WGSession>>(event, system.sessionConfig); return useSession<Partial<WGSession>>(event, system.sessionConfig);
} }

50
src/services/database/lowdb.ts

@ -201,47 +201,47 @@ export class LowDBClient extends ClientRepository {
} }
export default class LowDB extends DatabaseProvider { export default class LowDB extends DatabaseProvider {
#db!: Low<Database>; #db: Low<Database>;
#connected = false;
system!: LowDBSystem; system: LowDBSystem;
user!: LowDBUser; user: LowDBUser;
client!: LowDBClient; client: LowDBClient;
private constructor(db: Low<Database>) {
super();
this.#db = db;
this.system = new LowDBSystem(this.#db);
this.user = new LowDBUser(this.#db);
this.client = new LowDBClient(this.#db);
}
async runMigrations() {
await migrationRunner(this.#db);
}
/** /**
* @throws * @throws
*/ */
async connect() { static override async connect() {
if (this.#connected) {
return;
}
try { try {
DEBUG('Connecting'); DEBUG('Connecting...');
this.#db = await JSONFilePreset( const db = await JSONFilePreset(
'/etc/wireguard/db.json', '/etc/wireguard/db.json',
DEFAULT_DATABASE DEFAULT_DATABASE
); );
const inst = new LowDB(db);
DEBUG('Running Migrations'); DEBUG('Running Migrations...');
await migrationRunner(this.#db); await inst.runMigrations();
DEBUG('Migrations ran successfully'); DEBUG('Migrations ran successfully.');
DEBUG('Connected successfully.');
return inst;
} catch (e) { } catch (e) {
DEBUG(e); DEBUG(e);
throw new Error('Failed to initialize Database'); throw new Error('Failed to initialize Database');
} }
this.system = new LowDBSystem(this.#db);
this.user = new LowDBUser(this.#db);
this.client = new LowDBClient(this.#db);
this.#connected = true;
DEBUG('Connected successfully');
}
get connected() {
return this.#connected;
} }
async disconnect() { async disconnect() {
this.#connected = false;
DEBUG('Disconnected successfully'); DEBUG('Disconnected successfully');
} }
} }

4
src/services/database/repositories/database.ts

@ -28,7 +28,9 @@ export abstract class DatabaseProvider {
/** /**
* Connects to the database. * Connects to the database.
*/ */
abstract connect(): Promise<void>; static connect(): Promise<DatabaseProvider> {
throw new Error('Not implemented');
}
/** /**
* Disconnects from the database. * Disconnects from the database.

Loading…
Cancel
Save