59 lines
2.0 KiB
TypeScript
59 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { randomUUID } from "crypto";
|
|
import clientPromise from "./mongodb";
|
|
import { auth } from "./auth";
|
|
|
|
const DB = "dndextended";
|
|
|
|
export async function listContent(collection: string, req: NextRequest) {
|
|
const session = await auth();
|
|
if (!session) return NextResponse.json({ error: "Not Authenticated" }, { status: 401 });
|
|
|
|
const userId = session.user.id;
|
|
const url = new URL(req.url);
|
|
const scope = url.searchParams.get("scope") ?? "all";
|
|
|
|
const filter =
|
|
scope === "mine"
|
|
? { creatorId: userId }
|
|
: scope === "public"
|
|
? { visibility: "public" }
|
|
: { $or: [{ visibility: "public" }, { creatorId: userId }] };
|
|
|
|
const client = await clientPromise;
|
|
const results = await client.db(DB).collection(collection).find(filter).toArray();
|
|
return NextResponse.json({ results });
|
|
}
|
|
|
|
export async function createContent(collection: string, req: NextRequest) {
|
|
const session = await auth();
|
|
if (!session) return NextResponse.json({ error: "Not Authenticated" }, { status: 401 });
|
|
|
|
const userId = session.user.id;
|
|
const body = await req.json();
|
|
|
|
if (!body || typeof body !== "object") {
|
|
return NextResponse.json({ error: "Invalid body" }, { status: 400 });
|
|
}
|
|
if (!body.name || typeof body.name !== "string") {
|
|
return NextResponse.json({ error: "name required" }, { status: 400 });
|
|
}
|
|
|
|
const isAdmin = session.user.isAdmin === true;
|
|
const requestedPublic = body.visibility === "public";
|
|
const VALID_RULESETS = ["5e", "5.5e", "legacy", "homebrew"];
|
|
const requestedRuleset = VALID_RULESETS.includes(body.ruleset) ? body.ruleset : "5e";
|
|
const doc = {
|
|
...body,
|
|
id: body.id ?? randomUUID(),
|
|
creatorId: userId,
|
|
visibility: requestedPublic && isAdmin ? "public" : "private",
|
|
ruleset: isAdmin ? requestedRuleset : "homebrew",
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
|
|
const client = await clientPromise;
|
|
await client.db(DB).collection(collection).insertOne(doc);
|
|
return NextResponse.json({ result: doc }, { status: 201 });
|
|
}
|