Web app ready
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import db, { UPLOADS_DIR } from '@/lib/db';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_req: Request, { params }: Params) {
|
||||
const { id } = await params;
|
||||
const counter = db.prepare('SELECT * FROM counters WHERE id = ?').get(Number(id));
|
||||
if (!counter) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
return NextResponse.json(counter);
|
||||
}
|
||||
|
||||
export async function PUT(request: Request, { params }: Params) {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const existing = db.prepare('SELECT * FROM counters WHERE id = ?').get(Number(id)) as Record<string, unknown> | undefined;
|
||||
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
const name = body.name?.trim() ?? existing.name;
|
||||
const value = body.value !== undefined ? body.value : existing.value;
|
||||
const group_id = body.group_id !== undefined ? body.group_id : existing.group_id;
|
||||
const image_path = body.image_path !== undefined ? body.image_path : existing.image_path;
|
||||
|
||||
db.prepare(
|
||||
'UPDATE counters SET name = ?, value = ?, group_id = ?, image_path = ? WHERE id = ?'
|
||||
).run(name, value, group_id, image_path, Number(id));
|
||||
|
||||
const updated = db.prepare('SELECT * FROM counters WHERE id = ?').get(Number(id));
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
|
||||
export async function DELETE(_req: Request, { params }: Params) {
|
||||
const { id } = await params;
|
||||
const existing = db.prepare('SELECT * FROM counters WHERE id = ?').get(Number(id)) as Record<string, unknown> | undefined;
|
||||
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
// Remove associated image if present
|
||||
if (existing.image_path) {
|
||||
const imgFile = path.join(UPLOADS_DIR, path.basename(existing.image_path as string));
|
||||
try { fs.unlinkSync(imgFile); } catch { /* ignore missing file */ }
|
||||
}
|
||||
|
||||
db.prepare('DELETE FROM counters WHERE id = ?').run(Number(id));
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
Reference in New Issue
Block a user