Study/src/app/api/share/route.ts

52 lines
1.7 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { shareTargetSchema } from "@/lib/validation/shareSchemas";
import {
ShareTargetNotFoundError,
getShareLinkForContent,
isContentSharedViaGroup,
toggleShareLink,
} from "@/services/shareService";
export async function GET(request: NextRequest) {
const parsed = shareTargetSchema.safeParse(
Object.fromEntries(request.nextUrl.searchParams)
);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid share target" }, { status: 400 });
}
const { targetType, contentId } = parsed.data;
const link = await getShareLinkForContent(targetType, contentId);
if (targetType === "DECK" || targetType === "QUIZ") {
const groupShare = await isContentSharedViaGroup(targetType, contentId);
if (groupShare) {
return NextResponse.json({
token: groupShare.token,
isGroupShared: true,
groupName: groupShare.groupName,
});
}
}
return NextResponse.json({ token: link?.id ?? null, isGroupShared: false });
}
export async function POST(request: NextRequest) {
const parsed = shareTargetSchema.safeParse(
await request.json().catch(() => null)
);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid share target" }, { status: 400 });
}
try {
const link = await toggleShareLink(
parsed.data.targetType,
parsed.data.contentId
);
return NextResponse.json({ token: link?.id ?? null });
} catch (error) {
if (error instanceof ShareTargetNotFoundError) {
return NextResponse.json({ error: error.message }, { status: 404 });
}
console.error("Failed to update share link", error);
return NextResponse.json({ error: "Failed to update sharing" }, { status: 500 });
}
}