NeahNew/app/api/missions/image/[...path]/route.ts
2025-05-24 12:36:21 +02:00

66 lines
2.4 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) {
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_AWS_S3_UPLOAD_BUCKET_NAME || 'pages',
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 });
}
}