Browse Source

Feat: Improve Database Handling (#1383)

pull/1648/head
Bernd Storath 7 months ago
committed by Bernd Storath
parent
commit
b70b8d1500
  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;
}
const system = await Database.system.get();
if (!system)
throw createError({
statusCode: 500,
statusMessage: 'Invalid',
});
const session = await getSession(event, system.sessionConfig);
if (session.id && session.data.authenticated) {

18
src/server/utils/Database.ts

@ -5,11 +5,21 @@
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) => {
console.error(err);
process.exit(1);
// eslint-disable-next-line import/no-mutable-exports
let provider = nullObject as never as LowDb;
LowDb.connect().then((v) => {
provider = v;
WireGuard.Startup();
});
// 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));
}
DEBUG('Config saving...');
DEBUG('Saving Config...');
await fs.writeFile('/etc/wireguard/wg0.conf', result.join('\n\n'), {
mode: 0o600,
});
DEBUG('Config saved.');
DEBUG('Config saved successfully.');
}
async #syncWireguardConfig() {
DEBUG('Config syncing...');
DEBUG('Syncing Config...');
await wg.sync();
DEBUG('Config synced.');
DEBUG('Config synced successfully.');
}
async getClients() {
@ -275,16 +275,7 @@ class WireGuard {
}
async Startup() {
// TODO: improve this
await new Promise((res) => {
function wait() {
if (Database.connected) {
return res(true);
}
}
setTimeout(wait, 1000);
});
DEBUG('Starting Wireguard');
DEBUG('Starting Wireguard...');
await this.#saveWireguardConfig();
await wg.down().catch(() => {});
await wg.up().catch((err) => {
@ -301,10 +292,11 @@ class WireGuard {
throw err;
});
await this.#syncWireguardConfig();
DEBUG('Wireguard started successfully');
DEBUG('Wireguard started successfully.');
DEBUG('Starting Cron Job');
DEBUG('Starting Cron Job.');
await this.startCronJob();
DEBUG('Cron Job started successfully.');
}
async startCronJob() {
@ -426,10 +418,4 @@ class WireGuard {
}
}
const inst = new WireGuard();
inst.Startup().catch((v) => {
console.error(v);
process.exit(1);
});
export default inst;
export default new WireGuard();

1
src/server/utils/session.ts

@ -6,6 +6,5 @@ export type WGSession = {
export async function useWGSession(event: H3Event) {
const system = await Database.system.get();
if (!system) throw new Error('Invalid');
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 {
#db!: Low<Database>;
#connected = false;
#db: Low<Database>;
system!: LowDBSystem;
user!: LowDBUser;
client!: LowDBClient;
system: LowDBSystem;
user: LowDBUser;
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
*/
async connect() {
if (this.#connected) {
return;
}
static override async connect() {
try {
DEBUG('Connecting');
this.#db = await JSONFilePreset(
DEBUG('Connecting...');
const db = await JSONFilePreset(
'/etc/wireguard/db.json',
DEFAULT_DATABASE
);
DEBUG('Running Migrations');
await migrationRunner(this.#db);
DEBUG('Migrations ran successfully');
const inst = new LowDB(db);
DEBUG('Running Migrations...');
await inst.runMigrations();
DEBUG('Migrations ran successfully.');
DEBUG('Connected successfully.');
return inst;
} catch (e) {
DEBUG(e);
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() {
this.#connected = false;
DEBUG('Disconnected successfully');
}
}

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

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

Loading…
Cancel
Save