Files
Felix Schulze b02f5e6364
All checks were successful
Lint / Lint and Check (push) Successful in 51s
linter fixes, env fixes
2025-07-15 23:15:32 +02:00

61 lines
1.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { db, habits, users, habitLogs } from '@/lib/db';
import { getTokenCookie } from '@/lib/auth/cookies';
import { eq, and } from 'drizzle-orm';
async function getUserFromToken() {
const token = await getTokenCookie();
if (!token) return null;
const userRows = await db.select().from(users).where(eq(users.token, token));
return userRows.length > 0 ? userRows[0] : null;
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params;
const habitId = parseInt(id);
if (isNaN(habitId)) {
return NextResponse.json({ error: 'Invalid habit ID' }, { status: 400 });
}
const user = await getUserFromToken();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Verify habit belongs to user
const habitRows = await db
.select()
.from(habits)
.where(and(eq(habits.id, habitId), eq(habits.userId, user.id)));
if (habitRows.length === 0) {
return NextResponse.json({ error: 'Habit not found' }, { status: 404 });
}
const body = (await request.json()) as { note?: string };
const { note } = body;
// Create log entry
const logRows = await db
.insert(habitLogs)
.values({
habitId,
note,
})
.returning();
if (logRows.length === 0) {
throw new Error('Failed to create log entry');
}
const log = logRows[0];
return NextResponse.json({ log });
} catch (error) {
console.error('Log habit error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}