App

A lambda guestbook – Update

Only recent messages are now shown and the most recent messages will be sorted on top! Also, you can leave your pseudonym as author and the posts have a visible timestamp.

Check it out here: https://nickvanhoof.com/a-lambda-guestbook

A few weeks ago I created a guestbook linked to this website which uses AWS lambda’s and DynamoDB in the backend. You can read all about it here. As described above I now updated it.

What I changed

The lambda has to be able to query messages with a certain timestamp and sort them by date. In order to achieve this I had to restructure the database’s structure. I changed the unique-id (partition-key and sort-key) and added a GSI (global secondary index). With the table structure changed I am able to query the database from the query-lambda in a different way. In the parameters of the query I can now use the index and then create a KeyConditionExpression on this index.

The code that specifies the query parameters looks something like this:

let params = {
    TableName : "guestbook",
    IndexName: "YearMonthAttribute-Date-index",
    KeyConditionExpression: "YearMonthAttribute = :YMAttribute and #Dt > :date",
    ExpressionAttributeNames:{
        "#Dt": "Date"
    },
    ExpressionAttributeValues: {
        ":YMAttribute":  currentYearMonthAttribute,
        ":date": dateInMilliseconds
    },
    ProjectionExpression: "Author, Message, #Dt",
    ScanIndexForward: false
};

docClient.query(params, function(err, data) {
    if (err) {
        callback("Unable to query. Error: " + JSON.stringify(err, null, 2), null);
    } else {
        let numberOfResultsReturned = data.Count;
        console.log(`Query succeeded. Returned ${numberOfResultsReturned} results.`);
        callback(null, data);
    }
});

Code available on GitHub: https://github.com/Nxtra/Guestbook

One thought on “A lambda guestbook – Update

Leave a Reply

Your email address will not be published.