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

100% Statements 16/16
100% Branches 0/0
100% Functions 3/3
100% Lines 16/16

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 28 29 30 31 32 33 34 35 36                  2x 2x 1x 1x 1x   1x         4x 4x 3x   3x 3x 3x 2x 1x   1x   3x      
import { NextRequest, NextResponse } from "next/server";
import { requireAuth } from "@/lib/auth";
import { CollectionController } from "@/server/api/collections";
import { MemberController } from "@/server/api/members";
import { getDb } from "@/lib/db";
import { errorResponse } from "@/server/api/http-errors";
import { withTransaction } from "@/lib/transactions";
 
export async function GET() {
  try {
    const user = await requireAuth();
    const db = getDb();
    const collections = await CollectionController.fromDb(db).listCollections(user.id);
    return NextResponse.json(collections);
  } catch (error) {
    return errorResponse(error);
  }
}
 
export async function POST(request: NextRequest) {
  try {
    const user = await requireAuth();
    const body = await request.json();
 
    const db = getDb();
    const collection = await withTransaction(db, async (tx) => {
      const col = await CollectionController.fromDb(tx).createCollection(user.id, body);
      await MemberController.fromDb(tx).addOwner(col.id, user.id);
      return col;
    });
    return NextResponse.json(collection, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
}