espace-paie-odentas/app/api/documents/download/route.ts

67 lines
2 KiB
TypeScript

import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs'
import { cookies } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server'
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
const s3Client = new S3Client({
region: process.env.AWS_REGION || 'eu-west-3',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || '',
},
})
export async function GET(request: NextRequest) {
try {
const supabase = createRouteHandlerClient({ cookies })
// Vérifier l'authentification
const { data: { session } } = await supabase.auth.getSession()
if (!session) {
return new NextResponse('Unauthorized', { status: 401 })
}
const searchParams = request.nextUrl.searchParams
const path = searchParams.get('path')
if (!path) {
return new NextResponse('Missing path parameter', { status: 400 })
}
// Télécharger le fichier depuis S3
const command = new GetObjectCommand({
Bucket: process.env.AWS_S3_BUCKET_NAME || '',
Key: path,
})
const response = await s3Client.send(command)
if (!response.Body) {
return new NextResponse('File not found', { status: 404 })
}
// Convertir le stream en buffer
const chunks: Uint8Array[] = []
for await (const chunk of response.Body as any) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks)
// Extraire le nom du fichier depuis le path
const filename = path.split('/').pop() || 'document.txt'
// Retourner le fichier avec les bons headers pour forcer le téléchargement
return new NextResponse(buffer, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
})
} catch (error) {
console.error('Error in download route:', error)
return new NextResponse('Internal Server Error', { status: 500 })
}
}