2025-07-26 20:36:14 -05:00
|
|
|
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
|
|
|
|
|
import { Buffer } from 'node:buffer'
|
|
|
|
|
import { v4 as uuidv4 } from 'uuid'
|
2025-07-26 13:06:35 -05:00
|
|
|
|
|
|
|
|
class AWSUtil {
|
|
|
|
|
constructor() {
|
2025-07-26 20:36:14 -05:00
|
|
|
this.s3 = new S3Client({ region: 'us-east-2' })
|
2025-07-26 13:06:35 -05:00
|
|
|
}
|
|
|
|
|
|
2025-07-26 20:36:14 -05:00
|
|
|
async uploadFile(base64, ACL = 'public-read') {
|
|
|
|
|
const base64Data = Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ''), 'base64')
|
|
|
|
|
const type = base64.split(';')[0].split('/')[1]
|
|
|
|
|
const uuid = uuidv4()
|
2025-07-26 16:41:38 -05:00
|
|
|
|
2025-07-26 13:06:35 -05:00
|
|
|
const params = {
|
|
|
|
|
Bucket: process.env.AWS_S3_BUCKET,
|
2025-07-26 16:41:38 -05:00
|
|
|
Key: `${uuid}.${type}`,
|
2025-07-26 13:06:35 -05:00
|
|
|
Body: base64Data,
|
|
|
|
|
ContentEncoding: 'base64', // required
|
|
|
|
|
ContentType: `image/${type}` // required
|
2025-07-26 20:36:14 -05:00
|
|
|
}
|
2025-07-26 13:06:35 -05:00
|
|
|
|
2025-07-26 16:41:38 -05:00
|
|
|
// Create an object and upload it to the Amazon S3 bucket.
|
2025-07-26 13:06:35 -05:00
|
|
|
try {
|
2025-07-26 20:36:14 -05:00
|
|
|
const results = await this.s3.send(new PutObjectCommand(params))
|
2025-07-26 16:41:38 -05:00
|
|
|
console.log(
|
2025-07-26 20:36:14 -05:00
|
|
|
'Successfully created ' + params.Key + ' and uploaded it to ' + params.Bucket + '/' + params.Key
|
|
|
|
|
)
|
2025-07-26 16:41:38 -05:00
|
|
|
} catch (err) {
|
2025-07-26 20:36:14 -05:00
|
|
|
console.log('Error', err)
|
2025-07-26 13:06:35 -05:00
|
|
|
}
|
2025-07-26 16:41:38 -05:00
|
|
|
|
|
|
|
|
return `https://tattletires.s3.us-east-2.amazonaws.com/${params.Key}`
|
2025-07-26 13:06:35 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async deleteFile(Location) {
|
|
|
|
|
const params = {
|
|
|
|
|
Bucket: process.env.AWS_S3_BUCKET,
|
2025-07-26 20:36:14 -05:00
|
|
|
Key: Location.split('s3.amazonaws.com/').pop()
|
|
|
|
|
}
|
2025-07-26 13:06:35 -05:00
|
|
|
|
2025-07-26 20:36:14 -05:00
|
|
|
const data = await this.s3.deleteObject(params).promise()
|
2025-07-26 13:06:35 -05:00
|
|
|
|
2025-07-26 20:36:14 -05:00
|
|
|
return data
|
2025-07-26 13:06:35 -05:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-26 20:36:14 -05:00
|
|
|
export default AWSUtil
|