42 lines
1.6 KiB
TypeScript
42 lines
1.6 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { headers } from "next/headers";
|
|
import { auth } from "@/lib/auth";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { uploadFile, deleteFile } from "@/lib/s3";
|
|
import { randomUUID } from "crypto";
|
|
|
|
export async function POST(req: NextRequest) {
|
|
const session = await auth.api.getSession({ headers: await headers() });
|
|
if (!session || session.user.role !== "admin") {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const form = await req.formData();
|
|
const file = form.get("file") as File | null;
|
|
const lessonId = form.get("lessonId") as string | null;
|
|
if (!file || !lessonId) return NextResponse.json({ error: "Missing fields" }, { status: 400 });
|
|
|
|
const ext = file.name.split(".").pop() ?? "bin";
|
|
const key = `lessons/${lessonId}/${randomUUID()}.${ext}`;
|
|
const buffer = Buffer.from(await file.arrayBuffer());
|
|
const url = await uploadFile(key, buffer, file.type);
|
|
|
|
const lessonFile = await prisma.lessonFile.create({
|
|
data: { lessonId, name: file.name, url, size: file.size },
|
|
});
|
|
|
|
return NextResponse.json(lessonFile);
|
|
}
|
|
|
|
export async function DELETE(req: NextRequest) {
|
|
const session = await auth.api.getSession({ headers: await headers() });
|
|
if (!session || session.user.role !== "admin") {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const { fileId, key } = await req.json();
|
|
if (key) await deleteFile(key).catch(() => {});
|
|
await prisma.lessonFile.delete({ where: { id: fileId } });
|
|
return NextResponse.json({ ok: true });
|
|
}
|