44 lines
1.5 KiB
TypeScript
44 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { readConfig } from '@/lib/config'
|
|
import { createDbDumpBuffer } from '@/lib/backup'
|
|
import { requireAuth } from '@/lib/auth'
|
|
import pool from '@/lib/appDb'
|
|
|
|
// GET /api/db/backup?dbId=...
|
|
export async function GET(req: NextRequest) {
|
|
const authErr = await requireAuth(req)
|
|
if (authErr) return authErr
|
|
|
|
const { searchParams } = new URL(req.url)
|
|
const dbId = searchParams.get('dbId')
|
|
if (!dbId) return NextResponse.json({ error: 'Missing dbId' }, { status: 400 })
|
|
|
|
const config = await readConfig()
|
|
const db = config.databases.find(d => d.id === dbId)
|
|
if (!db) return NextResponse.json({ error: 'Database not found' }, { status: 404 })
|
|
|
|
try {
|
|
const buffer = await createDbDumpBuffer(db)
|
|
const dateStr = new Date().toISOString().replace(/[:.]/g, '-')
|
|
const filename = `${db.name}_${dateStr}.sql`
|
|
|
|
await pool.query(
|
|
`INSERT INTO backup_logs (db_id, status, message, file_size) VALUES ($1, $2, $3, $4)`,
|
|
[dbId, 'success', 'Manuel indirme', buffer.length]
|
|
)
|
|
|
|
return new NextResponse(new Uint8Array(buffer), {
|
|
headers: {
|
|
'Content-Type': 'application/octet-stream',
|
|
'Content-Disposition': `attachment; filename="${filename}"`,
|
|
},
|
|
})
|
|
} catch (e: any) {
|
|
await pool.query(
|
|
`INSERT INTO backup_logs (db_id, status, message, file_size) VALUES ($1, $2, $3, $4)`,
|
|
[dbId, 'error', e.message, 0]
|
|
)
|
|
return NextResponse.json({ error: e.message }, { status: 500 })
|
|
}
|
|
}
|