NeahNew/app/api/missions/image/[...path]/route.ts
2025-05-24 18:29:48 +02:00

89 lines
3.0 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 { NoSuchKey } from '@aws-sdk/client-s3';
// Initialize S3 client
const s3Client = new S3Client({
region: process.env.MINIO_AWS_REGION,
endpoint: process.env.MINIO_S3_UPLOAD_BUCKET_URL,
credentials: {
accessKeyId: process.env.MINIO_ACCESS_KEY || '',
secretAccessKey: process.env.MINIO_SECRET_KEY || ''
},
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) {
console.error('No path segments provided');
return new NextResponse('Path is required', { status: 400 });
}
// Reconstruct the full path from path segments
const filePath = pathSegments.join('/');
console.log('Fetching mission image:', {
originalPath: filePath,
segments: pathSegments
});
// Ensure the path has the missions/ prefix
const minioPath = filePath.startsWith('missions/') ? filePath : `missions/${filePath}`;
console.log('Full Minio path:', {
minioPath,
bucket: 'missions'
});
const command = new GetObjectCommand({
Bucket: 'missions',
Key: minioPath,
});
try {
const response = await s3Client.send(command);
if (!response.Body) {
console.error('File not found in Minio:', {
path: filePath,
minioPath,
bucket: 'missions',
contentType: response.ContentType
});
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,
path: filePath,
minioPath,
bucket: 'missions',
errorType: error instanceof NoSuchKey ? 'NoSuchKey' : 'Unknown'
});
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,
errorType: error instanceof Error ? error.constructor.name : typeof error,
message: error instanceof Error ? error.message : String(error)
});
return new NextResponse('Internal Server Error', { status: 500 });
}
}