/** * 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;