Skip to content

Instantly share code, notes, and snippets.

@SylarRuby
Last active December 13, 2022 17:11
Show Gist options
  • Select an option

  • Save SylarRuby/b3b1430ca633bc5ffec29bbcdac2bd52 to your computer and use it in GitHub Desktop.

Select an option

Save SylarRuby/b3b1430ca633bc5ffec29bbcdac2bd52 to your computer and use it in GitHub Desktop.

Revisions

  1. SylarRuby revised this gist Jul 14, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion deleteAvatar.js
    Original file line number Diff line number Diff line change
    @@ -23,7 +23,7 @@ const deletePhoto = async (avatar_url) => {

    // On around Line 41, you'll see how we stored the "Key"
    // see: https://gist.github.com/SylarRuby/b60eea29c1682519e422476cc5357b60
    const splitOn = `https://${S3_BUCKET.toLocaleLowerCase()}.s3.${S3_REGION.toLocaleLowerCase()}.amazonaws.com/`;
    const splitOn = `https://${S3_BUCKET.toLowerCase()}.s3.${S3_REGION.toLowerCase()}.amazonaws.com/`;
    const Key = avatar_url.split(splitOn)[1]; // The `${userId}.${type}`

    const params = {
  2. SylarRuby created this gist Jul 14, 2019.
    40 changes: 40 additions & 0 deletions deleteAvatar.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    /**
    * 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.toLocaleLowerCase()}.s3.${S3_REGION.toLocaleLowerCase()}.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;