Study/src/app/api/material-groups/route.ts
Elijah faaccf8a7e
All checks were successful
Automated Container Build / build-and-push (push) Successful in 1m8s
Changed: Show newly created material groups first and place uncategor -
2026-08-01 08:48:26 -07:00

57 lines
1.7 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import type { Prisma } from "@/generated/prisma/client";
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const classId = searchParams.get("classId");
const type = searchParams.get("type");
if (!classId) {
return NextResponse.json({ error: "classId is required" }, { status: 400 });
}
if (type && type !== "DECK" && type !== "QUIZ") {
return NextResponse.json({ error: "Invalid type" }, { status: 400 });
}
const whereClause: Prisma.MaterialGroupWhereInput = { classId };
if (type) {
whereClause.type = type;
}
try {
const groups = await prisma.materialGroup.findMany({
where: whereClause,
orderBy: [{ sortOrder: "desc" }, { createdAt: "desc" }],
});
return NextResponse.json(groups);
} catch (error) {
return NextResponse.json({ error: "Failed to fetch material groups" }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { classId, name, type } = body;
if (!classId || !name || (type !== "DECK" && type !== "QUIZ")) {
return NextResponse.json({ error: "Invalid input" }, { status: 400 });
}
const maxOrder = await prisma.materialGroup.aggregate({
where: { classId, type },
_max: { sortOrder: true },
});
const sortOrder = (maxOrder._max.sortOrder ?? -1) + 1;
const group = await prisma.materialGroup.create({
data: { classId, name, type, sortOrder },
});
return NextResponse.json(group, { status: 201 });
} catch (error) {
return NextResponse.json({ error: "Failed to create material group" }, { status: 500 });
}
}