70 lines
1.9 KiB
TypeScript
70 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { getPresignedUrl, getMultiplePresignedUrls } from '@/lib/s3';
|
|
|
|
/**
|
|
* Generate pre-signed URL(s) for S3 objects
|
|
* POST /api/s3/presigned-url
|
|
*
|
|
* Body:
|
|
* - Single key: { "key": "path/to/file.mp3", "expiresIn": 3600 }
|
|
* - Multiple keys: { "keys": ["path/file1.mp3", "path/file2.mp3"], "expiresIn": 3600 }
|
|
*/
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const { key, keys, expiresIn = 3600 } = body;
|
|
|
|
// Validate expiration time (max 7 days)
|
|
if (expiresIn > 604800) {
|
|
return NextResponse.json(
|
|
{ error: 'expiresIn cannot exceed 7 days (604800 seconds)' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Handle single key
|
|
if (key) {
|
|
if (typeof key !== 'string' || !key.trim()) {
|
|
return NextResponse.json(
|
|
{ error: 'Invalid key provided' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const url = await getPresignedUrl(key, expiresIn);
|
|
return NextResponse.json({ url, expiresIn }, { status: 200 });
|
|
}
|
|
|
|
// Handle multiple keys
|
|
if (keys) {
|
|
if (!Array.isArray(keys) || keys.length === 0) {
|
|
return NextResponse.json(
|
|
{ error: 'keys must be a non-empty array' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
if (keys.length > 100) {
|
|
return NextResponse.json(
|
|
{ error: 'Cannot generate more than 100 URLs at once' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const urls = await getMultiplePresignedUrls(keys, expiresIn);
|
|
return NextResponse.json({ urls, expiresIn }, { status: 200 });
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{ error: 'Either "key" or "keys" must be provided' },
|
|
{ status: 400 }
|
|
);
|
|
} catch (error: any) {
|
|
console.error('Presigned URL generation error:', error);
|
|
return NextResponse.json(
|
|
{ error: error.message || 'Failed to generate presigned URL' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|