Skip to content

Instantly share code, notes, and snippets.

@virtualprodigy
Last active June 5, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virtualprodigy/523ff0ac9e536bed8def8f4a79af5778 to your computer and use it in GitHub Desktop.
Save virtualprodigy/523ff0ac9e536bed8def8f4a79af5778 to your computer and use it in GitHub Desktop.
A simple Lambda function that will write/update/fetch a file on S3

How to Upload / Fetch a File To AWS S3

Below is a simple Lambda function that will write/update/fetch a file on S3. You'll need to provision your Lambda and S3 resources first or the execution will fail. This code was written for Node.js 8.10 Lambda in Javascript

console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context, callback) => {
    context.callbackWaitsForEmptyEventLoop = false;
    if (event.httpMethod == "GET") {
        return await getFile(callback);
    } else if (event.httpMethod == "PUT") {
        return await updateFile(event.body, callback);
    }

};

/**
 * Fetch the file from s3
 * */
async function getFile(callback) {
    const bucket = process.env.S3_BUCKET_NAME;
    const key = process.env.S3_KEY;
    const params = {
        Bucket: bucket,
        Key: key,
    };
    try {
        const object = await s3.getObject(params).promise();
        var file = object.Body.toString('ascii');
        var response = {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json"},
            "body": file,
            "isBase64Encoded": false
        };

        callback(null, response);
    } catch (err) {
        const message = `Error getting object ${key} from bucket ${bucket}.` +
            ` Make sure they exist and your bucket is in the same region as this` +
            `function. Error : ${err}`;
        var response = {
            "statusCode": 500,
            "headers": {"Content-Type": "application/json"},
            "body": JSON.stringify(message),
            "isBase64Encoded": false
        };

        console.log(message);
        callback(null, response);
        throw new Error(message);
    }
}

/**
 * Update the File stored in S3
 * */
async function updateFile(body, callback) {
    const bucket = process.env.S3_BUCKET_NAME;
    const key = process.env.S3_KEY;
    var params = {
        Body: body,
        Bucket: bucket,
        Key: key
    };

    try {
        const status = await s3.putObject(params).promise();
        console.log("status: ", status); // successful response
        var response = {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json"},
            "body": JSON.stringify({status}),
            "isBase64Encoded": false
        };
        callback(null, response);

    } catch (err) {
        const message = `Error putting object ${key} in bucket ${bucket}. Error : ${err}`;
        var response = {
            "statusCode": 500,
            "headers": {"Content-Type": "application/json"},
            "body": message,
            "isBase64Encoded": false
        };

        console.log(message);
        callback(null, response);
        throw new Error(message);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment