Files
image-apiv2/app/api/images/[id]/route.ts
Beyhan Oğur 71eff2d979 first commit
2026-04-26 22:09:32 +03:00

81 lines
2.0 KiB
TypeScript
Raw Permalink 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 { unlink } from "fs/promises";
import { join } from "path";
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];
// Dosyayı sil
try {
await unlink(imageData.filePath);
} catch (error) {
// Dosya bulunamazsa devam et (log production'da kaldırıldı)
}
// 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 }
);
}
}