Skip to content

Instantly share code, notes, and snippets.

@SylarRuby
Last active December 13, 2022 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save SylarRuby/b3b1430ca633bc5ffec29bbcdac2bd52 to your computer and use it in GitHub Desktop.
Save SylarRuby/b3b1430ca633bc5ffec29bbcdac2bd52 to your computer and use it in GitHub Desktop.
Deletes a s3 bucket object by a known unique key 💥
/**
* 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