|
| 1 | +// This file defines the API route for POST /api/reports |
| 2 | +// It lets logged-in users submit a report for a specific file. |
| 3 | + |
| 4 | +import { NextResponse } from "next/server"; // Used to send HTTP responses (JSON, status codes) |
| 5 | +import { z } from "zod"; // Zod validates and parses input data |
| 6 | + |
| 7 | +// Import database connection and the "report" table schema |
| 8 | +import { db } from "@src/server/db"; |
| 9 | +import { report } from "@src/server/db/schema/reports"; |
| 10 | + |
| 11 | +// Import session helper to check if a user is logged in |
| 12 | +import { getServerAuthSession } from "@src/server/auth"; |
| 13 | + |
| 14 | +// This ensures the API only accepts the correct fields |
| 15 | +const CreateReportSchema = z.object({ |
| 16 | + fileId: z.string().min(1), |
| 17 | + category: z |
| 18 | + .enum(["inappropriate", "copyright", "spam", "other"]) |
| 19 | + .default("other"), |
| 20 | + details: z.string().min(1), |
| 21 | +}); |
| 22 | + |
| 23 | +// This function runs when someone sends a POST request to /api/reports |
| 24 | +export async function POST(req: Request) { |
| 25 | + const session = await getServerAuthSession(); |
| 26 | + |
| 27 | + // If there’s no session or no user ID, reject the request |
| 28 | + if (!session?.user?.id) { |
| 29 | + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); |
| 30 | + } |
| 31 | + |
| 32 | + // Try to parse and validate the incoming request body |
| 33 | + let body: z.infer<typeof CreateReportSchema>; |
| 34 | + try { |
| 35 | + body = CreateReportSchema.parse(await req.json()); |
| 36 | + } catch (e) { |
| 37 | + return NextResponse.json( |
| 38 | + { error: "Invalid body", details: (e as Error).message }, |
| 39 | + { status: 400 } |
| 40 | + ); |
| 41 | + } |
| 42 | + |
| 43 | + // Insert the validated report into the database |
| 44 | + const [created] = await db |
| 45 | + .insert(report) |
| 46 | + .values({ |
| 47 | + userId: session.user.id, |
| 48 | + fileId: body.fileId, |
| 49 | + category: body.category, |
| 50 | + details: body.details, |
| 51 | + }) |
| 52 | + .returning(); // return the newly created record |
| 53 | + |
| 54 | + // Send the inserted report back as JSON |
| 55 | + return NextResponse.json(created, { status: 201 }); |
| 56 | +} |
0 commit comments