NeahNew/app/api/missions/image/[...path]/route.ts
2025-05-24 11:54:37 +02:00

67 lines
2.3 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';
import { NoSuchKey } from '@aws-sdk/client-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 {
const { path: pathSegments } = await params;
if (!pathSegments || pathSegments.length === 0) {
return new NextResponse('Path is required', { status: 400 });
}
// Reconstruct the full path from path segments
const filePath = pathSegments.join('/');
console.log('Fetching mission image:', filePath);
// Ensure the path has the missions/ prefix
const minioPath = filePath.startsWith('missions/') ? filePath : `missions/${filePath}`;
console.log('Full Minio path:', minioPath);
const command = new GetObjectCommand({
Bucket: process.env.MINIO_BUCKET_NAME || 'missions',
Key: minioPath,
});
try {
const response = await s3Client.send(command);
if (!response.Body) {
return new NextResponse('File not found', { status: 404 });
}
// Set appropriate content type and cache control
const contentType = response.ContentType || 'application/octet-stream';
const headers = new Headers();
headers.set('Content-Type', contentType);
headers.set('Cache-Control', 'public, max-age=31536000');
return new NextResponse(response.Body as any, { headers });
} catch (error) {
console.error('Error fetching file from Minio:', error);
if (error instanceof NoSuchKey) {
return new NextResponse('File not found', { status: 404 });
}
return new NextResponse('Internal Server Error', { status: 500 });
}
} catch (error) {
console.error('Error in image serving:', error);
return new NextResponse('Internal Server Error', { status: 500 });
}
}