Last active
December 13, 2022 17:11
-
-
Save SylarRuby/b3b1430ca633bc5ffec29bbcdac2bd52 to your computer and use it in GitHub Desktop.
Deletes a s3 bucket object by a known unique key π₯
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Delete an image from the S3 Bucket | |
* | |
* @author Daveyon Mayne <@MirMayne> | |
* @date July 14th 2019 | |
*/ | |
const AWS = require('aws-sdk'); | |
const deletePhoto = async (avatar_url) => { | |
if (!avatar_url) { | |
return console.log('No avatar_url found to delete π’'); | |
} | |
const { AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, S3_BUCKET, S3_REGION } = process.env; | |
AWS.config.setPromisesDependency(require('bluebird')); | |
AWS.config.update({ accessKeyId: AWS_ACCESS_KEY_ID, secretAccessKey: AWS_SECRET_ACCESS_KEY, region: S3_REGION }); | |
// Create an s3 instance | |
const s3 = new AWS.S3(); | |
// On around Line 41, you'll see how we stored the "Key" | |
// see: https://gist.github.com/SylarRuby/b60eea29c1682519e422476cc5357b60 | |
const splitOn = `https://${S3_BUCKET.toLowerCase()}.s3.${S3_REGION.toLowerCase()}.amazonaws.com/`; | |
const Key = avatar_url.split(splitOn)[1]; // The `${userId}.${type}` | |
const params = { | |
Bucket: S3_BUCKET, | |
Key, // required | |
}; | |
// More on the deleteObject property: | |
// see: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteObject-property | |
const data = await s3.deleteObject(params).promise(); | |
console.log(data); // => {} Empty object when successful | |
} | |
module.exports = deletePhoto; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment