Files
trackevery-day/app/api/habits/route.ts
2025-07-15 18:58:21 +02:00

106 lines
3.0 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, desc, sql } 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 GET(request: NextRequest) {
try {
const user = await getUserFromToken();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Get all non-archived habits with their latest log and statistics
const userHabits = await db
.select({
id: habits.id,
name: habits.name,
type: habits.type,
targetFrequency: habits.targetFrequency,
color: habits.color,
icon: habits.icon,
createdAt: habits.createdAt,
// Get the latest log time
lastLoggedAt: sql<Date>`(
SELECT MAX(logged_at)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
)`.as('lastLoggedAt'),
// Get total logs count
totalLogs: sql<number>`(
SELECT COUNT(*)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
)`.as('totalLogs'),
// Get logs in last 7 days
logsLastWeek: sql<number>`(
SELECT COUNT(*)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
AND logged_at >= NOW() - INTERVAL '7 days'
)`.as('logsLastWeek'),
// Get logs in last 30 days
logsLastMonth: sql<number>`(
SELECT COUNT(*)
FROM ${habitLogs}
WHERE habit_id = ${habits.id}
AND logged_at >= NOW() - INTERVAL '30 days'
)`.as('logsLastMonth'),
})
.from(habits)
.where(and(eq(habits.userId, user.id), eq(habits.isArchived, false)))
.orderBy(desc(habits.createdAt));
return NextResponse.json({ habits: userHabits });
} catch (error) {
console.error('Get habits error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const user = await getUserFromToken();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await request.json();
const { name, type, targetFrequency, color, icon } = body;
if (!name || !type) {
return NextResponse.json(
{
error: 'Name and type are required',
},
{ status: 400 },
);
}
const [newHabit] = await db
.insert(habits)
.values({
userId: user.id,
name,
type,
targetFrequency,
color,
icon,
})
.returning();
return NextResponse.json({ habit: newHabit });
} catch (error) {
console.error('Create habit error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}