| 1 | import { app } from 'electron'; |
| 2 | import path from 'path'; |
| 3 | import fs from 'fs/promises'; |
| 4 | import { exportDatabase, importDatabase } from '../../db'; |
| 5 | import { Injectable } from '../core/decorators'; |
| 6 | |
| 7 | @Injectable() |
| 8 | export class BackupService { |
| 9 | private backupDir: string; |
| 10 | |
| 11 | constructor() { |
| 12 | // 在用户数据目录下创建备份文件夹 |
| 13 | this.backupDir = path.join(app.getPath('userData'), 'backups'); |
| 14 | this.initBackupDir(); |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * 初始化备份目录 |
| 19 | */ |
| 20 | private async initBackupDir() { |
| 21 | try { |
| 22 | await fs.mkdir(this.backupDir, { recursive: true }); |
| 23 | } catch (error) { |
| 24 | console.error('Failed to create backup directory:', error); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * 创建备份 |
| 30 | * @param name 备份名称(可选) |
| 31 | * @returns 备份文件路径 |
| 32 | */ |
| 33 | async createBackup(name?: string): Promise<string> { |
| 34 | const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| 35 | const fileName = `${name ? name + '_' : ''}${timestamp}.sql`; |
| 36 | const backupPath = path.join(this.backupDir, fileName); |
| 37 | |
| 38 | try { |
| 39 | await exportDatabase(backupPath); |
| 40 | return backupPath; |
| 41 | } catch (error) { |
| 42 | console.error('Failed to create backup:', error); |
| 43 | throw error; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * 从备份文件恢复 |
| 49 | * @param backupPath 备份文件路径 |
| 50 | */ |
| 51 | async restoreFromBackup(backupPath: string): Promise<void> { |
| 52 | try { |
| 53 | await importDatabase(backupPath); |
| 54 | } catch (error) { |
| 55 | console.error('Failed to restore from backup:', error); |
| 56 | throw error; |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 |