Files
tally-counter/app/api/counters/[id]/log/route.ts
T
2026-08-25 13:58:29 +02:00

40 lines
1.7 KiB
TypeScript

import { NextResponse } from 'next/server';
import db from '@/lib/db';
export const dynamic = 'force-dynamic';
type Params = { params: Promise<{ id: string }> };
export async function POST(request: Request, { params }: Params) {
const { id } = await params;
const { date, delta } = await request.json();
if (!date || typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
return NextResponse.json({ error: 'Invalid date' }, { status: 400 });
}
if (delta !== 1 && delta !== -1) {
return NextResponse.json({ error: 'Delta must be 1 or -1' }, { status: 400 });
}
const existing = db.prepare('SELECT * FROM counters WHERE id = ? AND archived_at IS NULL').get(Number(id)) as Record<string, unknown> | undefined;
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 });
// Store at noon local server time so SQLite's 'localtime' grouping matches the picked date
const createdAt = new Date(`${date}T12:00:00`).getTime();
if (isNaN(createdAt)) return NextResponse.json({ error: 'Invalid date' }, { status: 400 });
const result = db.transaction(() => {
const updated = db.prepare(
delta === 1
? 'UPDATE counters SET value = value + 1 WHERE id = ? RETURNING *'
: 'UPDATE counters SET value = value - 1 WHERE id = ? AND value > 0 RETURNING *'
).get(Number(id)) as Record<string, unknown> | undefined;
if (!updated) return null;
db.prepare('INSERT INTO events (counter_id, delta, created_at) VALUES (?, ?, ?)').run(Number(id), delta, createdAt);
return updated;
})();
if (!result) return NextResponse.json({ error: 'Counter cannot go below 0' }, { status: 400 });
return NextResponse.json(result);
}