add services/mam-api/src/s3/client.js
This commit is contained in:
parent
e0f7f7c264
commit
8e247fe2ce
1 changed files with 62 additions and 0 deletions
62
services/mam-api/src/s3/client.js
Normal file
62
services/mam-api/src/s3/client.js
Normal file
|
|
@ -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;
|
||||
}
|
||||
};
|
||||
Loading…
Reference in a new issue