From 82d1e74af173f988d54598d9df7560f74f8b5ebf Mon Sep 17 00:00:00 2001 From: ZareMate <0.zaremate@gmail.com> Date: Mon, 12 May 2025 07:12:43 +0200 Subject: [PATCH] feat: refactor file download to use MinIO for file retrieval --- src/app/api/files/download/route.ts | 39 ++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/src/app/api/files/download/route.ts b/src/app/api/files/download/route.ts index a3af953..537e84b 100644 --- a/src/app/api/files/download/route.ts +++ b/src/app/api/files/download/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; -import path from "path"; -import { promises as fs } from "fs"; +import { db } from "~/server/db"; +import { minioClient } from "~/utils/minioClient"; export async function GET(req: Request) { const url = new URL(req.url); @@ -10,22 +10,43 @@ export async function GET(req: Request) { if (!fileId) { return NextResponse.json({ error: "File id is required" }, { status: 400 }); } - if (!fileName){ + if (!fileName) { return NextResponse.json({ error: "File name is required" }, { status: 400 }); } try { - const filePath = path.join(process.cwd(), "uploads", fileId); - const fileBuffer = await fs.readFile(filePath); + // Fetch file metadata from the database + const file = await db.file.findFirst({ + where: { id: fileId }, + }); - return new Response(fileBuffer, { + if (!file) { + return NextResponse.json({ error: "File not found" }, { status: 404 }); + } + + const bucketName = process.env.MINIO_BUCKET || "file-hosting"; + const objectName = `${file.id}-${file.name}`; // Construct the object name in MinIO + + // Fetch the file from MinIO + const stream = await minioClient.getObject(bucketName, objectName); + + // Return the file as a binary response + const readableStream = new ReadableStream({ + start(controller) { + stream.on("data", (chunk) => controller.enqueue(chunk)); + stream.on("end", () => controller.close()); + stream.on("error", (err) => controller.error(err)); + }, + }); + + return new Response(readableStream, { headers: { "Content-Type": "application/octet-stream", - "Content-Disposition": `attachment; filename="${fileName}" , fileId="${fileId}"`, + "Content-Disposition": `attachment; filename="${fileName}"`, }, }); } catch (error) { - console.error("Error reading file:", error); - return NextResponse.json({ error: "File not found" }, { status: 404 }); + console.error("Error fetching file from MinIO:", error); + return NextResponse.json({ error: "Failed to fetch file" }, { status: 500 }); } } \ No newline at end of file