AWS Lambda with S3

Other topics

Cheatsheet

AWS-SDK for javascript

Lambda contains aws-sdk (https://aws.amazon.com/sdk-for-node-js/) in its global so no need to upload this node-module into the zip.

const AWS = require('aws-sdk');

Sample function

module.exports.myFunction = (event, context, callback) => {
    const response = {
        statusCode: 200,
        body: 'Hello Lambda!',
    };
    return callback(null, response);
};

Running S3

const s3 = new AWS.S3();

Use with Elasticache Redis

//make sure redis node-module is added in zip
const redis = require('redis'); 
//the redis information should be stored in the environment, not hard coded
const redis_options = {
    host: process.env.REDIS_HOST,
    port: process.env.REDIS_PORT
};

module.exports.myFunction = (event, context, callback) => {
    try {
        let client = redis.createClient(redis_options);
        context.callbackWaitsForEmptyEventLoop = false;

        client.on('connect', () => {
            console.log('Connected:', client.connected);
        });

        client.on('end', () => {
            console.log('Connection closed.');
        });

        client.on('ready', function () {
            console.log('Connection ready.');
            client.keys('*', (err, keys) => {
            //always quit the redis client when no longer needed
            //else the connection will be used up
            client.quit(); 

            const response = {
                statusCode: 200,
                body: keys,
            };
            
            return callback(null, response);
        });
    } catch (err) {
        if (client) { client.quit();}
        console.log('Error!: ' + err.message);
        callback(err);
    }
};

Contributors

Topic Id: 9286

Example Ids: 28759

This site is not affiliated with any of the contributors.