db backup and restore implemented

This commit is contained in:
dimitar committed 2025-12-12 02:08:03 +01:00
1 parent 8353a24f6b
commit 19ec020046
18 files changed
+847 -118

No files matched your search

@@ -0,0 +1,47 @@
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
import { getDatabase, DatabaseFactory } from '@/lib/database'
import { ensureUserSynced } from '@/lib/sync-user'
import fs from 'fs'
import path from 'path'
const BACKUP_DIR = path.join(process.cwd(), 'backups')
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')
export async function POST(req: Request) {
try {
const { userId } = await auth()
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
const db = await getDatabase()
const user = await ensureUserSynced(userId, db)
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
return new NextResponse('Forbidden', { status: 403 })
}
const { filename } = await req.json()
if (!filename) {
return new NextResponse('Filename is required', { status: 400 })
}
const backupPath = path.join(BACKUP_DIR, filename)
if (!fs.existsSync(backupPath)) {
return new NextResponse('Backup file not found', { status: 404 })
}
// Close existing connection
await DatabaseFactory.disconnect()
// Restore file
fs.copyFileSync(backupPath, DB_PATH)
// Re-initialize connection (will happen automatically on next getDatabase call, but good to verify)
await getDatabase()
return NextResponse.json({ success: true })
} catch (error) {
console.error('Restore backup error:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}
@@ -0,0 +1,78 @@
import { auth } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
import { getDatabase } from '@/lib/database'
import { ensureUserSynced } from '@/lib/sync-user'
import fs from 'fs'
import path from 'path'
const BACKUP_DIR = path.join(process.cwd(), 'backups')
const DB_PATH = path.join(process.cwd(), 'data', 'fitai.db')
export async function GET() {
try {
const { userId } = await auth()
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
const db = await getDatabase()
const user = await ensureUserSynced(userId, db)
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
return new NextResponse('Forbidden', { status: 403 })
}
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true })
}
const files = fs.readdirSync(BACKUP_DIR)
.filter(file => file.endsWith('.db'))
.map(file => {
const stats = fs.statSync(path.join(BACKUP_DIR, file))
return {
name: file,
size: stats.size,
createdAt: stats.birthtime
}
})
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
return NextResponse.json(files)
} catch (error) {
console.error('List backups error:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}
export async function POST() {
try {
const { userId } = await auth()
if (!userId) return new NextResponse('Unauthorized', { status: 401 })
const db = await getDatabase()
const user = await ensureUserSynced(userId, db)
if (!user || (user.role !== 'admin' && user.role !== 'superAdmin')) {
return new NextResponse('Forbidden', { status: 403 })
}
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true })
}
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const backupPath = path.join(BACKUP_DIR, `backup-${timestamp}.db`)
// Ensure source DB exists
if (!fs.existsSync(DB_PATH)) {
return new NextResponse('Database file not found', { status: 404 })
}
// Copy file
fs.copyFileSync(DB_PATH, backupPath)
return NextResponse.json({ success: true, filename: `backup-${timestamp}.db` })
} catch (error) {
console.error('Create backup error:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}
@@ -5,7 +5,7 @@ import { getDatabase } from '@/lib/database';
// POST - Mark goal as complete
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
@@ -5,7 +5,7 @@ import { getDatabase } from '@/lib/database';
// GET - Get specific goal
export async function GET(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
@@ -40,7 +40,7 @@ export async function GET(
// PUT - Update goal
export async function PUT(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();
@@ -82,7 +82,7 @@ export async function PUT(
// DELETE - Delete goal
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string } }
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { userId } = await auth();