2

I have written a lambda function to copy a file to another s3 bucket and delete the object from current bucket, but it is stooped at some line and not executed after that. I tried below two options, first one stops at a line second one finishes but response is not coming to API gateway proxy

    var AWS = require("aws-sdk");
    
    
    // Main Lambda entry point
    exports.handler = async (event) => {
          await getUploadURL(event);
          
            var responseBody = {
            "status": "success",
            "message": "The file was successfully moved"
        };
            const response = {
            "statusCode": 200,
            "headers": {
                "Content-Type": "application/json",
                "Access-Control-Allow-Headers": "Content-Type",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE"
            },
            "body": JSON.stringify(responseBody),
            "isBase64Encoded": false
        };
        return response;
      };
    
    const getUploadURL = async function(event) {
        console.log("invoking lambda starting");
        var s3 = new AWS.S3();
        var sourceBucket = "sourcebucket";
        var destinationBucket = "destbucket";
        var objectKey = event.queryStringParameters.fileName;
        console.log("Object Key", objectKey);
        //Only execute till here after that no execution log
        var copySource = encodeURI(sourceBucket + "/" + objectKey);
        var copyParams = {
            Bucket: destinationBucket,
            CopySource: copySource,
            Key: objectKey
        };
        var deleteParams = {
            Bucket: sourceBucket,
            Key: objectKey
        };
       /** var responseBody = {
            "status": "success",
            "message": "The file was successfully marked as read"
        };
        var failedResponseBody = {
            "status": "Failed",
            "message": "The file was not copied"
        };**/
      await s3.copyObject(copyParams, function (err, data) {
            console.log("Starting Copying function");
            if (err) {
                console.log("error occured during copy", err, err.stack);
            } else {
                console.log("The copy was successful, response");
            }
        });
    
        await s3.deleteObject(deleteParams, function (err, data) {
            console.log("Deleting the file from S3");
            if (err)
                console.log(err, err.stack); // error
            else
                console.log("Deleted the File from S3"); // deleted
                
              
        });
    
        
    };

I tried another option with call back, it is working but the lambda is not returning proper response. The file is moved but the response to API gateway is coming as null. The API is complaining with 502 for invalid response

 var AWS = require("aws-sdk");
exports.handler = (event, context, callback) => {
    console.log("invoking lambda starting")
    var s3 = new AWS.S3();
    var sourceBucket = "source";
    var destinationBucket = "destination";
    var objectKey = event.queryStringParameters.fileName
    console.log("Object Key", objectKey)
    var copySource = encodeURI(sourceBucket + "/" + objectKey);
    var copyParams = {
        Bucket: destinationBucket,
        CopySource: copySource,
        Key: objectKey
    };
    var deleteParams = {
        Bucket: sourceBucket,
        Key: objectKey
    }
    var responseBody = {
        "status": "success",
        "message": "The file was successfully marked as read"
    };
    var failedResponseBody = {
        "status": "Failed",
        "message": "The file was not copied"
    };
   s3.copyObject(copyParams, function (err, data) {
        console.log("Starting Copying function");
        if (err) {
            console.log("error occured during copy", err, err.stack);
        } else {
            console.log("The copy was successful, response", response);
        }
    });

    s3.deleteObject(deleteParams, function (err, data) {
        console.log("Deleting the file from S3");
        if (err)
            console.log(err, err.stack); // error
        else
            console.log("Deleted the File from S3"); // deleted
    });


    const response = {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE"
        },
        "body": JSON.stringify(responseBody),
        "isBase64Encoded": false
    };
    return callback(response);
};
1
  • Could you please properly format your code? It's really hard to read and understand because the indentation of your lines is mixed up. Commented Feb 24, 2021 at 8:16

1 Answer 1

1

Just a quick check right now but I can see the following problems:

Example code 1: You are mixing callback and await/async style. If you want to use async/await, use this pattern:

const copyResult = await s3.copyObject(props).promise();
const deleteResult = await s3.deleteObject(props2).promise();
// ...

Example code 2: Your code is using callbacks but you're continuing with your code without waiting for the callback to happen. Use this pattern:

exports.handler = (event, context, callback) => {
  const props = { ... };
  s3.copyObject(props, (err, data) => {
    if (err) {
      // ...
    } else {
      const props2 = { ... };
      s3.deleteObject(props2, (err2, data2) => {
        if (err2) {
          // ...
        } else {
          callback(response);
        }
      });
    }
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.