Files
ERitors-Scribe-Desktop/electron/database/database.service.ts
natreex 515d469ba7 Add multi-language support and new repository methods for book synchronization
- Extend repository methods to handle API requests for fetching books, chapters, characters, and other entities with multilingual support (`lang: 'fr' | 'en'`).
- Add `uploadBookForSync` logic to consolidate and decrypt book data for synchronization.
- Refactor schema migration logic to remove console logs and streamline table recreation.
- Enhance error handling across database repositories and IPC methods.
2025-12-22 16:44:12 -05:00

94 lines
2.4 KiB
TypeScript

import sqlite3 from 'node-sqlite3-wasm';
import path from 'path';
import { app } from 'electron';
import { initializeSchema, runMigrations } 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();
}
const userDataPath:string = app.getPath('userData');
const dbPath:string = path.join(userDataPath, `eritors-local.db`);
this.db = new sqlite3.Database(dbPath);
this.userEncryptionKey = encryptionKey;
this.userId = userId;
initializeSchema(this.db);
runMigrations(this.db);
}
/**
* 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;
}