LoginSignup
5
2

More than 5 years have passed since last update.

js初学者がDynamoDBの値をlambdaで加算してみた。

Last updated at Posted at 2016-06-07

はじめに

最近流行りのAWSを触ってみました。
jsは、初めてですので文法ミス等有ると思いますが、見つけたらコメントなどでご指摘ください。

メモ

以下のようなjsonを渡されたとき

  • JSON
{
    "userid" : "peta727",
    "count" : "1"
}

userid のDynamoDB上のcountを count 分だけ数値を加算します。

この場合は、 userid がDynamoDBのテーブルのプライマリキーです。

  • lambda
'use strict';
console.log('Loading function');
var aws = require('aws-sdk');
var dynamo = new aws.DynamoDB({region: 'ap-northeast-1'});

exports.handler = (event, context, callback) => {
    dynamo.updateItem(
        {
            "TableName":"peta727-dynamodb-table",
            "Key" : {
                "userid" : {"S": event.userid}
            },
            "ExpressionAttributeNames" : {
                "#count" : "count"
            },
            "ExpressionAttributeValues" : {
                        ":i" : {"N" : event.count},
                        ":default": {"N" : "0"}
            },
            "UpdateExpression" :  "set #count = if_not_exists(#count, :default) + :i",
            "ReturnValues":"ALL_NEW"
        }, function(err, data) {
            if (err) {
                console.log("error: " + err);
                context.fail();
            } else {
                console.log("data uploaded successfulle." + JSON.stringify(data));
                context.succeed();
            }
        });
};

実際、触ってはいませんが ALL_NEW で更新後の値を返しているので再びDBを叩くことなく更新後の値を使用することができると思います。

  • 返り値

//返り値
{
    "Attributes":{
        "count":{"N":"5"},
        "userid":{"S":"peta727"}
    }
}
5
2
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
5
2