bagsy/apps/api/app/api/lists/route.ts

74 lines
2 KiB
TypeScript

import { NextRequest } from 'next/server';
import { requireAuth, getActiveHousehold } from '@/lib/auth-middleware';
import { successResponse, errorResponse, handleError } from '@/lib/response';
import { db } from '@/db';
import { shoppingLists, listItems } from '@/db/schema';
import { eq } from 'drizzle-orm';
/**
* GET /api/lists
* List all shopping lists for the current household
*/
async function GET() {
try {
await requireAuth();
const household = await getActiveHousehold();
const lists = await db
.select()
.from(shoppingLists)
.where(eq(shoppingLists.householdId, household.id));
// For each list, fetch items
const listsWithItems = await Promise.all(
lists.map(async (list) => {
const items = await db
.select()
.from(listItems)
.where(eq(listItems.shoppingListId, list.id));
return { ...list, items };
})
);
return successResponse(listsWithItems);
} catch (error) {
return handleError(error);
}
}
/**
* POST /api/lists
* Create a new shopping list
* Body: { name: string, storeId: string, isPreset?: boolean, autoReset?: boolean }
*/
async function POST(req: NextRequest) {
try {
await requireAuth();
const household = await getActiveHousehold();
const body = await req.json();
if (!body.name || typeof body.name !== 'string') {
return errorResponse('INVALID_INPUT', 'List name is required');
}
if (!body.storeId || typeof body.storeId !== 'string') {
return errorResponse('INVALID_INPUT', 'Store ID is required');
}
const [list] = await db
.insert(shoppingLists)
.values({
householdId: household.id,
storeId: body.storeId,
name: body.name,
isPreset: body.isPreset || false,
autoReset: body.autoReset || false,
})
.returning();
return successResponse({ ...list, items: [] }, 201);
} catch (error) {
return handleError(error);
}
}
export { GET, POST };