NeahNew/app/api/missions/image/[...path]/route.ts
2025-05-06 22:13:34 +02:00

68 lines
2.2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/options';
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
import { S3_CONFIG } from '@/lib/s3';
// Initialize S3 client
const s3Client = new S3Client({
region: S3_CONFIG.region,
endpoint: S3_CONFIG.endpoint,
credentials: {
accessKeyId: S3_CONFIG.accessKey || '',
secretAccessKey: S3_CONFIG.secretKey || ''
},
forcePathStyle: true // Required for MinIO
});
// This endpoint serves mission images from Minio using the server's credentials
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ path: string[] }> }
) {
try {
// Await the params promise to get the actual path parameter
const { path } = await params
// Check if path is provided
if (!path || path.length === 0) {
return new NextResponse('Path is required', { status: 400 });
}
// Reconstruct the full path from path segments
const filePath = path.join('/');
console.log('Fetching mission image:', filePath);
// Create S3 command to get the object
const command = new GetObjectCommand({
Bucket: S3_CONFIG.bucket, // Use the pages bucket
Key: filePath,
});
// Get the object from S3/Minio
const response = await s3Client.send(command);
if (!response.Body) {
console.error('File not found in Minio:', filePath);
return new NextResponse('File not found', { status: 404 });
}
// Get the readable web stream directly
const stream = response.Body.transformToWebStream();
// Determine content type
const contentType = response.ContentType || 'application/octet-stream';
// Create and return a new response with the file stream
return new NextResponse(stream as ReadableStream, {
headers: {
'Content-Type': contentType,
'Cache-Control': 'public, max-age=31536000', // Cache for 1 year
},
});
} catch (error) {
console.error('Error serving mission image:', error);
console.error('Error details:', JSON.stringify(error, null, 2));
return new NextResponse('Internal Server Error', { status: 500 });
}
}