data export and backup utilities

This commit is contained in:
2025-02-04 09:51:26 +01:00
parent 6341148118
commit 1484d051a1
2 changed files with 133 additions and 0 deletions

49
lib/backup-utils.ts Normal file
View File

@@ -0,0 +1,49 @@
import { exec } from 'child_process'
import path from 'path'
import { promisify } from 'util'
const execAsync = promisify(exec)
export async function createDatabaseBackup(): Promise<string> {
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
const backupPath = path.join(process.cwd(), 'backups', `backup_${Date.now()}.db`)
try {
// Ensure backup directory exists
await execAsync('mkdir -p backups')
// Create SQLite backup using .backup command
await execAsync(`sqlite3 "${dbPath}" ".backup '${backupPath}'"`)
return backupPath
} catch (error) {
console.error('Backup failed:', error)
throw new Error('Database backup failed')
}
}
export async function restoreDatabase(backupPath: string): Promise<void> {
const dbPath = path.join(process.cwd(), 'database', 'antihoax.db')
try {
// Create backup of current DB first
await createDatabaseBackup()
// Copy backup to main location
await execAsync(`cp "${backupPath}" "${dbPath}"`)
console.log('Database restored successfully')
} catch (error) {
console.error('Restore failed:', error)
throw new Error('Database restore failed')
}
}
export async function listBackups(): Promise<string[]> {
try {
const { stdout } = await execAsync('ls -la backups/*.db 2>/dev/null || true')
return stdout.trim() ? stdout.trim().split('\n') : []
} catch {
return []
}
}