0
votes

I am creating a personal Alexa skill that can log in the savings that i have on a daily basis. So lets say I saved 10$ today, i want my alexa skill to remember that along with a running sum of the total money that i have saved so far, so if yesterday i had saved 5$, if i ask the skill about my savings, it should come back with 15$. I also want it to have the capability, to subtract from the total sum when i withdraw money. So if i take out 5$ tomorrow, the new total should be 10$.

I have done the Alexa part of the skill, where i am able to get the amount in the var, varUserAmount in my lambda function. But i am stuck beyond that. I was also able to make the following query work, where everytime i say an amount the value gets written in the dynamodb.

var params = {
 TableName: 'AccountManagement',
 Item: {
 'date' : {S: 'test'},
 'amount' : {N: varUserAmount},
 }
};

// Call DynamoDB to add the item to the table
 ddb.putItem(params, function(err, data) {
 if (err) {
  console.log("Error", err);
 } else {
 console.log("Success", data);
  }
});

My confusion is on the query side of the things, how would the total column in the table work? I would assume i would want to query the last value of the total, add the new amount from the user, and write the updated total amount back to the table? But i am not sure how to write that query to get the latest value of total?

Any guidance would be appreciated.

1
What is the primary key of your DynamoDB table? If the key is a compound key with something like AccountID as the partition key, and date as the sort key, then you could query by AccountID, with ScanIndexForward = false and Limit = 1 to get the last record inserted for that account.Mark B
do you want to keep the history of movements (additions and subtractions) or just the total amount at present ?Sébastien Stormacq
i would be fine with having just the total amount presentMuneeb Rehman

1 Answers

3
votes

As you commented you do not need to keep the history of movement, the simplest way to achieve your objective is to use the ADD operation on an UPDATE API call.

Here is a sample code that works :

// create table with 
//
// aws dynamodb create-table --table-name demo --key-schema AttributeName=id,KeyType=HASH --attribute-definitions AttributeName=id,AttributeType=N --billing-mode PAY_PER_REQUEST

const AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
const documentClient = new AWS.DynamoDB.DocumentClient();

const TABLE_NAME = 'demo';

async function insertOrUpdateDDB(userId, value) {

    return new Promise((resolve, reject) => {

        var params = {
            TableName: TABLE_NAME,
            Key: {
                id: userId
            },
            UpdateExpression: "ADD amount :val",
            ExpressionAttributeValues: {
                ":val": value
            }
        };

        documentClient.update(params, (err, data) => {
            if (err) {
                console.log("Error when calling DynamoDB");
                console.log(err, err.stack); // an error occurred
                reject(err);
            } else {
                //console.log(data); // successful response
                resolve(data);
            }
        });
    });
}

async function readDDB(userId) {

    return new Promise((resolve, reject) => {
        var params = {
            TableName: TABLE_NAME,
            Key: {
                id: userId
            }
        };

        documentClient.get(params, (err, data) => {
            if (err) {
                console.log("Error when calling DynamoDB");
                console.log(err, err.stack); // an error occurred
                reject(err);
            } else {
                //console.log(data); // successful response
                resolve(data);
            }
        });
    });
}

async function main() {
    console.log("adding 150 to the amount");
    await insertOrUpdateDDB(1, 150);

    console.log("removing 50 from the amount");
    await insertOrUpdateDDB(1, -50);

    console.log("querying the amount");
    let data = await readDDB(1);
    console.log(JSON.stringify(data,null,2));
}    

main();

which produces :

$ node so.js
adding 150 to the amount
removing 50 from the amount
querying the amount
{
  "Item": {
    "id": 1,
    "amount": 100
  }
}