|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { Image, IMAGES_API_ENDPOINT } from "@/types"; |
| 3 | +import { deleteFile, uploadFile } from "@/lib/s3"; |
| 4 | +import { mapUrlsToKeys } from "@/helpers"; |
| 5 | + |
| 6 | +export async function POST(req: NextRequest) { |
| 7 | + try { |
| 8 | + const formData = await req.formData(); |
| 9 | + const files = formData.getAll(IMAGES_API_ENDPOINT) as File[]; |
| 10 | + |
| 11 | + const uploadPromises = files.map(async (file) => { |
| 12 | + const buffer = await file.arrayBuffer(); |
| 13 | + const fileName = `${Date.now()}-${file.name}`; |
| 14 | + const mimeType = file.type; |
| 15 | + |
| 16 | + await uploadFile({ |
| 17 | + file: Buffer.from(buffer), |
| 18 | + fileName, |
| 19 | + mimeType, |
| 20 | + }); |
| 21 | + |
| 22 | + const url = `https://${process.env.S3_BUCKET_NAME}.s3.${process.env.MY_AWS_REGION}.amazonaws.com/${fileName}`; |
| 23 | + |
| 24 | + return { |
| 25 | + url, |
| 26 | + name: file.name, |
| 27 | + }; |
| 28 | + }); |
| 29 | + |
| 30 | + const uploadedImages: Image[] = await Promise.all(uploadPromises); |
| 31 | + |
| 32 | + return NextResponse.json({ success: true, data: uploadedImages }); |
| 33 | + } catch (error) { |
| 34 | + console.error("Upload images error:", error); |
| 35 | + return NextResponse.json({ success: false, error: "Image upload failed" }); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +export async function DELETE(req: NextRequest) { |
| 40 | + try { |
| 41 | + const { urls } = await req.json(); |
| 42 | + |
| 43 | + // Extract and decode the keys from the URLs |
| 44 | + const keys = mapUrlsToKeys(urls); |
| 45 | + |
| 46 | + await Promise.all(keys.map((key) => deleteFile({ key }))); |
| 47 | + |
| 48 | + return NextResponse.json({ success: true }); |
| 49 | + } catch (error) { |
| 50 | + console.error("Image deletion error:", error); |
| 51 | + return NextResponse.json({ |
| 52 | + success: false, |
| 53 | + error: "Image deletion failed", |
| 54 | + }); |
| 55 | + } |
| 56 | +} |
0 commit comments