voxblog/apps/api/src/storage/s3.ts

37 lines
1.0 KiB
TypeScript

import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
function getS3Client() {
const endpoint = process.env.S3_ENDPOINT; // e.g. http://<VPS_IP>:9000
const region = process.env.S3_REGION || 'us-east-1';
const accessKeyId = process.env.S3_ACCESS_KEY || '';
const secretAccessKey = process.env.S3_SECRET_KEY || '';
if (!endpoint || !accessKeyId || !secretAccessKey) {
throw new Error('Missing S3 config: S3_ENDPOINT, S3_ACCESS_KEY, S3_SECRET_KEY');
}
return new S3Client({
region,
endpoint,
forcePathStyle: true,
credentials: { accessKeyId, secretAccessKey },
});
}
export async function uploadBuffer(params: {
bucket: string;
key: string;
body: Buffer;
contentType?: string;
}) {
const s3 = getS3Client();
const cmd = new PutObjectCommand({
Bucket: params.bucket,
Key: params.key,
Body: params.body,
ContentType: params.contentType || 'application/octet-stream',
});
await s3.send(cmd);
return { bucket: params.bucket, key: params.key };
}