dragonflight/services/mam-api/src/s3/client.js

67 lines
1.8 KiB
JavaScript
Raw Normal View History

2026-04-07 21:58:26 -04:00
import { S3Client, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { Upload } from '@aws-sdk/lib-storage';
export const S3_BUCKET = process.env.S3_BUCKET || 'mam';
2026-04-07 21:58:26 -04:00
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,
},
forcePathStyle: true,
requestChecksumCalculation: "WHEN_REQUIRED",
responseChecksumValidation: "WHEN_REQUIRED",
2026-04-07 21:58:26 -04:00
});
export { s3Client };
export const getSignedUrlForObject = async (key, expiresIn = 3600, contentType = null) => {
2026-04-07 21:58:26 -04:00
try {
const params = { Bucket: S3_BUCKET, Key: key };
if (contentType) params.ResponseContentType = contentType;
const command = new GetObjectCommand(params);
2026-04-07 21:58:26 -04:00
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: S3_BUCKET,
2026-04-07 21:58:26 -04:00
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: S3_BUCKET,
2026-04-07 21:58:26 -04:00
Key: key,
});
const result = await s3Client.send(command);
return result;
} catch (err) {
console.error('Error deleting from S3:', err);
throw err;
}
};