Files
image-apiv3/app/api/images/[id]/route.ts
Beyhan Oğur 031582ea2c first commit
2026-04-26 22:11:03 +03:00

81 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/db";
import { images } from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { auth } from "@/app/lib/auth";
import { deleteFromR2 } from "@/app/lib/r2-storage";
async function getUserId(request: NextRequest): Promise<string | null> {
try {
const session = await auth.api.getSession({
headers: request.headers,
});
return session?.user?.id || null;
} catch {
return null;
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> | { id: string } }
) {
try {
const userId = await getUserId(request);
if (!userId) {
return NextResponse.json(
{ message: "Yetkisiz erişim" },
{ status: 401 }
);
}
// Next.js 15'te params async olabilir
const resolvedParams = await Promise.resolve(params);
const imageId = resolvedParams.id;
// Input validation
if (!imageId || typeof imageId !== "string" || imageId.length > 255) {
return NextResponse.json(
{ message: "Geçersiz resim ID" },
{ status: 400 }
);
}
// Resmi veritabanından bul
const image = await db
.select()
.from(images)
.where(and(eq(images.id, imageId), eq(images.userId, userId)))
.limit(1);
if (image.length === 0) {
return NextResponse.json(
{ message: "Resim bulunamadı veya yetkiniz yok" },
{ status: 404 }
);
}
const imageData = image[0];
// R2'den dosyayı sil
try {
await deleteFromR2(imageData.fileName);
} catch (error) {
console.error("R2'den silme hatası:", error);
// Hata olsa bile devam et, veritabanından sil
}
// Veritabanından sil
await db.delete(images).where(eq(images.id, imageId));
return NextResponse.json({
message: "Resim başarıyla silindi",
});
} catch (error: any) {
return NextResponse.json(
{ message: "Silme işlemi başarısız" },
{ status: 500 }
);
}
}