53 lines
1.9 KiB
TypeScript
53 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { requireAdmin } from '@/lib/admin-auth'
|
|
import { createServiceClient } from '@/lib/supabase'
|
|
|
|
const BUCKET = 'hero-bilder'
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const check = await requireAdmin()
|
|
if (check instanceof NextResponse) return check
|
|
|
|
const db = createServiceClient()
|
|
const formData = await req.formData()
|
|
const file = formData.get('file') as File
|
|
if (!file) return NextResponse.json({ error: 'file erforderlich' }, { status: 400 })
|
|
|
|
const ext = file.name.split('.').pop()?.toLowerCase() ?? 'jpg'
|
|
const path = `bg-${Date.now()}.${ext}`
|
|
|
|
const { data: existing } = await db.from('hero_content').select('bg_image_path').limit(1).single()
|
|
if (existing?.bg_image_path) {
|
|
await db.storage.from(BUCKET).remove([existing.bg_image_path])
|
|
}
|
|
|
|
const { error: uploadError } = await db.storage
|
|
.from(BUCKET)
|
|
.upload(path, file, { contentType: file.type, upsert: true })
|
|
if (uploadError) return NextResponse.json({ error: uploadError.message }, { status: 500 })
|
|
|
|
const { data: row } = await db.from('hero_content').select('id').limit(1).single()
|
|
const op = row
|
|
? db.from('hero_content').update({ bg_image_path: path }).eq('id', row.id)
|
|
: db.from('hero_content').insert({ bg_image_path: path })
|
|
const { error } = await op
|
|
if (error) return NextResponse.json({ error: error.message }, { status: 500 })
|
|
|
|
return NextResponse.json({ path })
|
|
}
|
|
|
|
export async function DELETE() {
|
|
const check = await requireAdmin()
|
|
if (check instanceof NextResponse) return check
|
|
|
|
const db = createServiceClient()
|
|
const { data: existing } = await db.from('hero_content').select('id, bg_image_path').limit(1).single()
|
|
if (existing?.bg_image_path) {
|
|
await db.storage.from(BUCKET).remove([existing.bg_image_path])
|
|
}
|
|
if (existing?.id) {
|
|
await db.from('hero_content').update({ bg_image_path: null }).eq('id', existing.id)
|
|
}
|
|
return NextResponse.json({ success: true })
|
|
}
|