64 lines
2.3 KiB
TypeScript
64 lines
2.3 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { requireRole } from '@/lib/auth';
|
|
import { db } from '@/lib/db';
|
|
|
|
export async function GET() {
|
|
try {
|
|
await requireRole('admin');
|
|
const { rows } = await db.query('SELECT id, filename, category, room_id, location_target, uploaded_at FROM images ORDER BY uploaded_at DESC');
|
|
return NextResponse.json({ images: rows, count: rows.length });
|
|
} catch (error) {
|
|
if ((error as Error).message === 'Unauthorized') {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
console.error('List images error:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
await requireRole('admin');
|
|
const body = await request.json();
|
|
const { filename, data, category, room_id, location_target } = body;
|
|
|
|
if (!filename || !data) {
|
|
return NextResponse.json({ error: 'Missing filename or data' }, { status: 400 });
|
|
}
|
|
|
|
const { rows } = await db.query(
|
|
'INSERT INTO images (filename, data, category, room_id, location_target) VALUES ($1, $2, $3, $4, $5) RETURNING id, filename, category, room_id, location_target, uploaded_at',
|
|
[filename, data, category || 'other', room_id || null, location_target || 'gallery']
|
|
);
|
|
|
|
return NextResponse.json({ image: rows[0] });
|
|
} catch (error) {
|
|
if ((error as Error).message === 'Unauthorized') {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
console.error('Upload image error:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
export async function DELETE(request: NextRequest) {
|
|
try {
|
|
await requireRole('admin');
|
|
const { searchParams } = new URL(request.url);
|
|
const id = searchParams.get('id');
|
|
|
|
if (!id) {
|
|
return NextResponse.json({ error: 'Missing id' }, { status: 400 });
|
|
}
|
|
|
|
await db.query('DELETE FROM images WHERE id = $1', [id]);
|
|
return NextResponse.json({ ok: true });
|
|
} catch (error) {
|
|
if ((error as Error).message === 'Unauthorized') {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
console.error('Delete image error:', error);
|
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
|
}
|
|
}
|