96 lines
2.4 KiB
TypeScript
96 lines
2.4 KiB
TypeScript
import sqlite3 from 'node-sqlite3-wasm';
|
|
import path from 'path';
|
|
import { app } from 'electron';
|
|
import { initializeSchema } from './schema.js';
|
|
|
|
// Type alias for compatibility
|
|
export type Database = sqlite3.Database;
|
|
|
|
/**
|
|
* DatabaseService - Manages SQLite database connection ONLY
|
|
* No business logic, no CRUD operations
|
|
* Just connection management and encryption key storage
|
|
*/
|
|
export class DatabaseService {
|
|
private db: Database | null = null;
|
|
private userEncryptionKey: string | null = null;
|
|
private userId: string | null = null;
|
|
|
|
constructor() {}
|
|
|
|
/**
|
|
* Initialize the database for a specific user
|
|
* @param userId - User ID for encryption key
|
|
* @param encryptionKey - User's encryption key (generated at first login)
|
|
*/
|
|
initialize(userId: string, encryptionKey: string): void {
|
|
if (this.db) {
|
|
this.close();
|
|
}
|
|
|
|
// Get user data directory
|
|
const userDataPath = app.getPath('userData');
|
|
const dbPath = path.join(userDataPath, `eritors-local-${userId}.db`);
|
|
|
|
this.db = new sqlite3.Database(dbPath);
|
|
this.userEncryptionKey = encryptionKey;
|
|
this.userId = userId;
|
|
|
|
// Initialize schema
|
|
initializeSchema(this.db);
|
|
|
|
console.log(`Database initialized for user ${userId} at ${dbPath}`);
|
|
}
|
|
|
|
/**
|
|
* Close the database connection
|
|
*/
|
|
close(): void {
|
|
if (this.db) {
|
|
this.db.close();
|
|
this.db = null;
|
|
this.userEncryptionKey = null;
|
|
this.userId = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if database is initialized
|
|
*/
|
|
isInitialized(): boolean {
|
|
return this.db !== null && this.userEncryptionKey !== null;
|
|
}
|
|
|
|
/**
|
|
* Get database connection
|
|
* Use this in repositories and model classes
|
|
*/
|
|
getDb(): Database | null {
|
|
return this.db;
|
|
}
|
|
|
|
/**
|
|
* Get user encryption key
|
|
*/
|
|
getEncryptionKey(): string | null {
|
|
return this.userEncryptionKey;
|
|
}
|
|
|
|
/**
|
|
* Get current user ID
|
|
*/
|
|
getUserId(): string | null {
|
|
return this.userId;
|
|
}
|
|
}
|
|
|
|
// Singleton instance
|
|
let dbServiceInstance: DatabaseService | null = null;
|
|
|
|
export function getDatabaseService(): DatabaseService {
|
|
if (!dbServiceInstance) {
|
|
dbServiceInstance = new DatabaseService();
|
|
}
|
|
return dbServiceInstance;
|
|
}
|