From 8e247fe2ce3cf80ae48d056d08238f141415a657 Mon Sep 17 00:00:00 2001 From: Zac Gaetano Date: Tue, 7 Apr 2026 21:58:26 -0400 Subject: [PATCH] add services/mam-api/src/s3/client.js --- services/mam-api/src/s3/client.js | 62 +++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 services/mam-api/src/s3/client.js diff --git a/services/mam-api/src/s3/client.js b/services/mam-api/src/s3/client.js new file mode 100644 index 0000000..b197a95 --- /dev/null +++ b/services/mam-api/src/s3/client.js @@ -0,0 +1,62 @@ +import { S3Client, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import { Upload } from '@aws-sdk/lib-storage'; + +const s3Client = new S3Client({ + region: process.env.S3_REGION || 'us-east-1', + endpoint: process.env.S3_ENDPOINT, + credentials: { + accessKeyId: process.env.S3_ACCESS_KEY, + secretAccessKey: process.env.S3_SECRET_KEY, + }, +}); + +export { s3Client }; + +export const getSignedUrlForObject = async (key, expiresIn = 3600) => { + try { + const command = new GetObjectCommand({ + Bucket: process.env.S3_BUCKET, + Key: key, + }); + const url = await getSignedUrl(s3Client, command, { expiresIn }); + return url; + } catch (err) { + console.error('Error generating signed URL:', err); + throw err; + } +}; + +export const uploadStream = async (key, stream, contentType) => { + try { + const upload = new Upload({ + client: s3Client, + params: { + Bucket: process.env.S3_BUCKET, + Key: key, + Body: stream, + ContentType: contentType, + }, + }); + + const result = await upload.done(); + return result; + } catch (err) { + console.error('Error uploading to S3:', err); + throw err; + } +}; + +export const deleteObject = async (key) => { + try { + const command = new DeleteObjectCommand({ + Bucket: process.env.S3_BUCKET, + Key: key, + }); + const result = await s3Client.send(command); + return result; + } catch (err) { + console.error('Error deleting from S3:', err); + throw err; + } +};