initial webapp
This commit is contained in:
55
app/api/habits/[id]/log/route.ts
Normal file
55
app/api/habits/[id]/log/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
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 [user] = await db.select().from(users).where(eq(users.token, token));
|
||||
return user;
|
||||
}
|
||||
|
||||
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 [habit] = await db
|
||||
.select()
|
||||
.from(habits)
|
||||
.where(and(eq(habits.id, habitId), eq(habits.userId, user.id)));
|
||||
|
||||
if (!habit) {
|
||||
return NextResponse.json({ error: 'Habit not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { note } = body;
|
||||
|
||||
// Create log entry
|
||||
const [log] = await db
|
||||
.insert(habitLogs)
|
||||
.values({
|
||||
habitId,
|
||||
note,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json({ log });
|
||||
} catch (error) {
|
||||
console.error('Log habit error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user