|
| 1 | +import mime from "mime-types"; |
| 2 | +import { eq } from "drizzle-orm"; |
| 3 | +import { type NextRequest, NextResponse } from "next/server"; |
| 4 | +import { blob } from "@/drizzle/schema"; |
| 5 | +import { headObject } from "@/lib/blobStore"; |
| 6 | +import { database } from "@/lib/utils/useDatabase"; |
| 7 | +import { getOwner } from "@/lib/utils/useOwner"; |
| 8 | + |
| 9 | +export type ConfirmResponse = { |
| 10 | + url: string; |
| 11 | +}; |
| 12 | + |
| 13 | +export async function POST(request: NextRequest) { |
| 14 | + const { userId } = await getOwner(); |
| 15 | + |
| 16 | + const body = await request.json(); |
| 17 | + const { fileId } = body as { fileId: string }; |
| 18 | + |
| 19 | + if (!fileId) { |
| 20 | + return NextResponse.json( |
| 21 | + { error: "Missing fileId" }, |
| 22 | + { status: 400 }, |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + const db = database(); |
| 27 | + |
| 28 | + try { |
| 29 | + const [blobRecord] = await db |
| 30 | + .select() |
| 31 | + .from(blob) |
| 32 | + .where(eq(blob.id, fileId)) |
| 33 | + .limit(1); |
| 34 | + |
| 35 | + if (!blobRecord) { |
| 36 | + return NextResponse.json({ error: "File not found" }, { status: 404 }); |
| 37 | + } |
| 38 | + |
| 39 | + if (blobRecord.createdByUser !== userId) { |
| 40 | + return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); |
| 41 | + } |
| 42 | + |
| 43 | + if (blobRecord.status === "confirmed") { |
| 44 | + const extension = mime.extension(blobRecord.contentType); |
| 45 | + return NextResponse.json<ConfirmResponse>({ |
| 46 | + url: `${process.env.NEXT_PUBLIC_APP_URL}/api/blob/${fileId}/file.${extension}`, |
| 47 | + }); |
| 48 | + } |
| 49 | + |
| 50 | + const exists = await headObject(blobRecord.key); |
| 51 | + if (!exists) { |
| 52 | + return NextResponse.json( |
| 53 | + { error: "File not uploaded to storage" }, |
| 54 | + { status: 400 }, |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + await db |
| 59 | + .update(blob) |
| 60 | + .set({ |
| 61 | + status: "confirmed", |
| 62 | + updatedAt: new Date(), |
| 63 | + }) |
| 64 | + .where(eq(blob.id, fileId)) |
| 65 | + .execute(); |
| 66 | + |
| 67 | + const extension = mime.extension(blobRecord.contentType); |
| 68 | + return NextResponse.json<ConfirmResponse>({ |
| 69 | + url: `${process.env.NEXT_PUBLIC_APP_URL}/api/blob/${fileId}/file.${extension}`, |
| 70 | + }); |
| 71 | + } catch (error) { |
| 72 | + console.error("Error confirming upload", error); |
| 73 | + return NextResponse.json( |
| 74 | + { error: "Failed to confirm upload" }, |
| 75 | + { status: 500 }, |
| 76 | + ); |
| 77 | + } |
| 78 | +} |
0 commit comments