36 lines
1.3 KiB
TypeScript
36 lines
1.3 KiB
TypeScript
import { HttpError } from "@/lib/errors";
|
|
import { route } from "@/lib/http";
|
|
import { deleteImage, listImages, saveUpload } from "@/lib/images";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
type Ctx = { params: Promise<{ slug: string }> };
|
|
|
|
export const GET = route<Ctx>(async (_req, { params }) => {
|
|
const { slug } = await params;
|
|
return Response.json({ files: await listImages(slug) });
|
|
});
|
|
|
|
/** multipart/form-data with one or more `file` fields. */
|
|
export const POST = route<Ctx>(async (req, { params }) => {
|
|
const { slug } = await params;
|
|
const form = await req.formData().catch(() => {
|
|
throw new HttpError(400, "expected multipart/form-data");
|
|
});
|
|
const files = form.getAll("file").filter((f): f is File => f instanceof File);
|
|
if (!files.length) throw new HttpError(400, "no files uploaded");
|
|
|
|
const saved = [];
|
|
for (const file of files) saved.push(await saveUpload(slug, file));
|
|
return Response.json({ saved, files: await listImages(slug) }, { status: 201 });
|
|
});
|
|
|
|
/** Query: ?name=<file name> */
|
|
export const DELETE = route<Ctx>(async (req, { params }) => {
|
|
const { slug } = await params;
|
|
const name = new URL(req.url).searchParams.get("name");
|
|
if (!name) throw new HttpError(400, "name is required");
|
|
await deleteImage(slug, name);
|
|
return Response.json({ files: await listImages(slug) });
|
|
});
|