LoginSignup
15
16

More than 5 years have passed since last update.

S3にアップロードしたファイルをLambdaで処理してDynamoDBに入れる

Posted at

S3 -> Lambda -> DynamoDBという流れでデータを放り込む算段です。データ量によってはタイムアウトするかも(タイムアウトしてて手元では動いてません…)。

前提

  • IAMロールなどは適切に設定してください

LambdaでS3のイベントを処理するサンプル

var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });
var dynamodb = new aws.DynamoDB({region: 'ap-northeast-1'});

exports.handler = function(event, context) {
    // Get the object from the event and show its content type
    var bucket = event.Records[0].s3.bucket.name;
    var key = event.Records[0].s3.object.key;
    var params = {
        Bucket: bucket,
        Key: key
    };

    // Retrieve object from S3
    s3.getObject(params, function(err, data) {
        if (err) {
            console.log(err);
            var message = "Error getting object " + key + " from bucket " + bucket +
                ". Make sure they exist and your bucket is in the same region as this function.";
            console.log(message);
            context.fail(message);
        } else {
            // ファイルのバイナリは data.Body に入っている
            var string = data.Body.toString('utf-8');
            var payload = JSON.parse(string);

            // 型を付ける必要があるかも
            // Object.keys(payload).forEach(function(key) {
            //     payload[key] = {'N': String(payload[key])};
            // });

            dynamodb.putItem({"TableName":"s3-upload-history",
                "Item": payload
            }

            context.succeed(data.ContentType);
        }
    });
};

Lambdaの設定

  • Event Source Type -> S3
  • Bucket -> 任意
  • Event Type -> Object Created
  • Prefix -> 任意のパス
  • Suffix -> 任意の拡張子
15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16