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';
|
|
|
|
|
|
2026-04-07 22:05:40 -04:00
|
|
|
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,
|
|
|
|
|
},
|
2026-04-07 22:05:40 -04:00
|
|
|
forcePathStyle: true,
|
2026-05-19 22:47:33 -04:00
|
|
|
requestChecksumCalculation: "WHEN_REQUIRED",
|
|
|
|
|
responseChecksumValidation: "WHEN_REQUIRED",
|
2026-04-07 21:58:26 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export { s3Client };
|
|
|
|
|
|
2026-05-19 22:47:33 -04:00
|
|
|
export const getSignedUrlForObject = async (key, expiresIn = 3600, contentType = null) => {
|
2026-04-07 21:58:26 -04:00
|
|
|
try {
|
2026-05-19 22:47:33 -04:00
|
|
|
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: {
|
2026-04-07 22:05:40 -04:00
|
|
|
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({
|
2026-04-07 22:05:40 -04:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
};
|