Files
tally-counter/app/api/counters/[id]/route.ts
T
2026-06-06 17:14:53 +02:00

50 lines
2.1 KiB
TypeScript

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 });
}