feat: add navigation between submissions, enable image zoom, and automate cleanup of deleted form images
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
"use server";
|
||||
|
||||
import { db } from "@/db";
|
||||
import { unlink } from "fs/promises";
|
||||
import path from "path";
|
||||
import { questions } from "@/db/schema";
|
||||
import type { QuestionType } from "@/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
@@ -53,13 +55,40 @@ export async function updateQuestion(
|
||||
}>
|
||||
) {
|
||||
await assertAdmin();
|
||||
if (data.imageUrl !== undefined) {
|
||||
const q = await db.query.questions.findFirst({
|
||||
where: (q, { eq }) => eq(q.id, id),
|
||||
});
|
||||
if (q?.imageUrl && q.imageUrl !== data.imageUrl) {
|
||||
await deleteImageFile(q.imageUrl);
|
||||
}
|
||||
}
|
||||
await db.update(questions).set(data).where(eq(questions.id, id));
|
||||
revalidatePath("/form");
|
||||
revalidatePath("/form/admin");
|
||||
}
|
||||
|
||||
async function deleteImageFile(imageUrl: string | null) {
|
||||
if (!imageUrl) return;
|
||||
try {
|
||||
const filename = imageUrl.split("/").pop();
|
||||
if (filename) {
|
||||
const filepath = path.join(process.cwd(), "public", "form", filename);
|
||||
await unlink(filepath);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to delete image file", err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteQuestion(id: string, formId: string) {
|
||||
await assertAdmin();
|
||||
const q = await db.query.questions.findFirst({
|
||||
where: (q, { eq }) => eq(q.id, id),
|
||||
});
|
||||
if (q?.imageUrl) {
|
||||
await deleteImageFile(q.imageUrl);
|
||||
}
|
||||
await db.delete(questions).where(eq(questions.id, id));
|
||||
revalidatePath("/form");
|
||||
revalidatePath("/form/admin");
|
||||
|
||||
@@ -22,11 +22,11 @@ export async function uploadImage(formData: FormData): Promise<string> {
|
||||
|
||||
const ext = file.name.split(".").pop() ?? "png";
|
||||
const filename = `${crypto.randomUUID()}.${ext}`;
|
||||
const uploadDir = path.join(process.cwd(), "public", "form-uploads");
|
||||
const uploadDir = path.join(process.cwd(), "public", "form");
|
||||
|
||||
await mkdir(uploadDir, { recursive: true });
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
await writeFile(path.join(uploadDir, filename), buffer);
|
||||
|
||||
return `/form-uploads/${filename}`;
|
||||
return `/form/${filename}`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user