55 lines
2.2 KiB
TypeScript
55 lines
2.2 KiB
TypeScript
"use server";
|
|
|
|
import { db } from "@/db";
|
|
import { forms } from "@/db/schema";
|
|
import { eq } from "drizzle-orm";
|
|
import { revalidatePath } from "next/cache";
|
|
import { redirect } from "next/navigation";
|
|
import { getServerSession } from "next-auth";
|
|
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
|
|
|
export async function createForm(formData: FormData) {
|
|
const session = await getServerSession(authOptions);
|
|
const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
const discordId = (session?.user as { discordId?: string } | undefined)?.discordId;
|
|
if (!discordId || !adminIds.includes(discordId)) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
const title = formData.get("title") as string;
|
|
const description = formData.get("description") as string | null;
|
|
|
|
const [form] = await db
|
|
.insert(forms)
|
|
.values({ title, description: description ?? null })
|
|
.returning();
|
|
|
|
revalidatePath("/form/admin");
|
|
redirect(`/form/admin/${form.id}/edit`);
|
|
}
|
|
|
|
export async function updateForm(id: string, data: { title?: string; description?: string | null; isOpen?: boolean; discordWebhookUrl?: string | null; discordWebhookTemplate?: string | null; discordWebhookUpdateTemplate?: string | null }) {
|
|
const session = await getServerSession(authOptions);
|
|
const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
const discordId = (session?.user as { discordId?: string } | undefined)?.discordId;
|
|
if (!discordId || !adminIds.includes(discordId)) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
await db.update(forms).set(data).where(eq(forms.id, id));
|
|
revalidatePath("/form");
|
|
revalidatePath("/form/admin");
|
|
}
|
|
|
|
export async function deleteForm(id: string) {
|
|
const session = await getServerSession(authOptions);
|
|
const adminIds = (process.env.ADMIN_DISCORD_IDS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
const discordId = (session?.user as { discordId?: string } | undefined)?.discordId;
|
|
if (!discordId || !adminIds.includes(discordId)) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
await db.delete(forms).where(eq(forms.id, id));
|
|
revalidatePath("/admin/form");
|
|
}
|