All files / src/app/api/sessions route.ts

100% Statements 14/14
100% Branches 6/6
100% Functions 1/1
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                14x 14x   13x 13x 12x 12x 12x   9x 9x 6x       3x      
import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { getSession } from "@/lib/auth";
import { requireApiCollectionAccess } from "@/server/dal/collection-access";
import { SessionController } from "@/server/api/sessions";
import { errorResponse } from "@/server/api/http-errors";
 
export async function POST(req: NextRequest) {
  const session = await getSession();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
 
  const { collectionId, goal } = await req.json();
  if (!collectionId) return NextResponse.json({ error: "collectionId is required" }, { status: 400 });
  const db = getDb();
  const access = await requireApiCollectionAccess(db, collectionId, session.user.id);
  if (access instanceof NextResponse) return access;
 
  try {
    const newSession = await SessionController.fromDb(db).createSession(collectionId, session.user.id, { goal });
    return NextResponse.json(newSession, { status: 201 });
  } catch (error) {
    // CurrentSessionExistsError -> gentle 409 (existing sort in this slot:
    // active / paused / completed / set-aside). Other errors keep their mapping.
    return errorResponse(error);
  }
}