initial commit
This commit is contained in:
35
app/api/images/[slug]/route.ts
Normal file
35
app/api/images/[slug]/route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
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) });
|
||||
});
|
||||
Reference in New Issue
Block a user