59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import fs from 'fs/promises';
|
|
import { prisma } from '@/lib/prisma';
|
|
import { getFullAttachmentPath } from '@/lib/storage';
|
|
|
|
export async function GET(
|
|
req: NextRequest,
|
|
context: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id } = await context.params;
|
|
const attachment = await prisma.attachment.findUnique({
|
|
where: { id },
|
|
});
|
|
|
|
if (!attachment) {
|
|
return NextResponse.json({ error: 'Attachment not found' }, { status: 404 });
|
|
}
|
|
|
|
const fullPath = getFullAttachmentPath(attachment.storagePath);
|
|
const fileBuf = await fs.readFile(fullPath);
|
|
|
|
const download = req.nextUrl.searchParams.get('download') === '1';
|
|
const disposition = download ? 'attachment' : 'inline';
|
|
const safeFilename = encodeURIComponent(attachment.filename);
|
|
|
|
return new NextResponse(fileBuf, {
|
|
status: 200,
|
|
headers: {
|
|
'Content-Type': attachment.mimeType || 'application/octet-stream',
|
|
'Content-Length': String(fileBuf.length),
|
|
'Content-Disposition': `${disposition}; filename*=UTF-8''${safeFilename}`,
|
|
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
},
|
|
});
|
|
} catch (err: unknown) {
|
|
return NextResponse.json(
|
|
{ error: err instanceof Error ? err.message : 'Failed to stream attachment' },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function DELETE(
|
|
_req: NextRequest,
|
|
context: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id } = await context.params;
|
|
await prisma.attachment.delete({ where: { id } });
|
|
return NextResponse.json({ deleted: true });
|
|
} catch (err: unknown) {
|
|
return NextResponse.json(
|
|
{ error: err instanceof Error ? err.message : 'Failed to delete attachment' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|