任何人都可以提供动态文档客户端upsert的示例吗?

时间:2017-05-01 22:28:43

标签: node.js amazon-dynamodb

我在AWS dynamodb's DocumentClient节点中寻找一个非平凡的upsert示例。有人可以分享一个适合他们的样本吗?

我想看一个在创建记录时设置created_at,updated_at和id字段的示例,但只在找到并更新记录时设置updated_at。

1 个答案:

答案 0 :(得分:5)

这应该达到你的目标。我很抱歉,因为我在原帖中错过了你的标准。我假设id是您表格中的关键。

'use strict';

var AWS = require('aws-sdk');
var ec2 = new AWS.EC2({ apiVersion: '2016-09-15' });
var ddb = new AWS.DynamoDB.DocumentClient();
AWS.config.region = 'us-east-1';

var ret = {};
const ddbTbl = 'table_name';

var date = new Date();
var dateAsIso = date.toISOString();

exports.handler = (event, context, callback) => {
    var key = 'bar';
    var params = {
        TableName: ddbTbl,
        Key: {
            "id": key
        },
        UpdateExpression: "set #u = :t, #c = if_not_exists(#c, :t)",
        ExpressionAttributeNames: {
            "#u": "updated_at",
            "#c": "created_at"
        },
        ExpressionAttributeValues: {
            ":t": dateAsIso
        },
        ReturnValues: "UPDATED_NEW"
    };
    ddb.update(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
            ret.ddbUpdate = err;
            callback(null, {success: false, message: ["ddb upsert failed"], payload: ret});
            // or use the regular callback for failures if you don't want to do your own envelope response
        } else {
            console.log(data);
            ret.ddbUpdate = data;
            callback(null, {success: true, message: ["ddb upsert succeeded"], payload: ret});
        }
    });
};