use bun's s3 client

This commit is contained in:
Oliver Bryan
2026-01-08 11:05:10 +00:00
parent fa47359d68
commit d40b71f619
4 changed files with 7 additions and 229 deletions

View File

@@ -1,7 +1,6 @@
import { randomUUID } from "node:crypto";
import { PutObjectCommand } from "@aws-sdk/client-s3";
import type { BunRequest } from "bun";
import { bucketName, s3Client, s3Endpoint, s3PublicUrl } from "../../s3";
import { s3Client, s3Endpoint, s3PublicUrl } from "../../s3";
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
@@ -34,23 +33,14 @@ export default async function uploadAvatar(req: BunRequest) {
return new Response("invalid file extension", { status: 400 });
}
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
const uuid = randomUUID();
const key = `avatars/${uuid}.${fileExtension}`;
const publicUrlBase = s3PublicUrl || s3Endpoint;
const publicUrl = `${publicUrlBase}/${key}`;
try {
await s3Client.send(
new PutObjectCommand({
Bucket: bucketName,
Key: key,
Body: buffer,
ContentType: file.type,
}),
);
const s3File = s3Client.file(key);
await s3File.write(file, { type: file.type });
} catch (error) {
console.error("failed to upload to S3:", error);
return new Response("failed to upload image", { status: 500 });

View File

@@ -1,4 +1,4 @@
import { S3Client } from "@aws-sdk/client-s3";
import { S3Client } from "bun";
const s3Endpoint = process.env.S3_ENDPOINT;
const s3AccessKeyId = process.env.S3_ACCESS_KEY_ID;
@@ -12,11 +12,9 @@ if (!s3Endpoint || !s3AccessKeyId || !s3SecretAccessKey || !s3BucketName) {
export const s3Client = new S3Client({
endpoint: s3Endpoint,
region: "auto",
credentials: {
accessKeyId: s3AccessKeyId,
secretAccessKey: s3SecretAccessKey,
},
bucket: s3BucketName,
accessKeyId: s3AccessKeyId,
secretAccessKey: s3SecretAccessKey,
});
export const bucketName = s3BucketName;