DynamoDB CRUD operations using AWS lambda and nodeJS

DynamoDB CRUD operations using AWS lambda and nodeJS

DynamoDB is a fully managed NoSQL database service provided by Amazon Web Services (AWS) that allows for the creation and operation of high-performance tables. One of the key benefits of DynamoDB is its seamless integration with other AWS services, such as AWS Lambda. In this article, we will discuss how to perform CRUD (Create, Read, Update, and Delete) operations on DynamoDB tables using AWS Lambda.

First, let's look at how to create a new table in DynamoDB using AWS Lambda. The AWS SDK for JavaScript in Node.js provides a DynamoDB client that can be used to create a new table. The following example demonstrates how to create a new table named "myTable" with a primary key named "id":

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB({region: 'us-west-2', apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    const params = {
        TableName: "myTable",
        KeySchema: [
            { AttributeName: "id", KeyType: "HASH"}
        ],
        AttributeDefinitions: [
            { AttributeName: "id", AttributeType: "S" }
        ],
        ProvisionedThroughput: {
            ReadCapacityUnits: 10,
            WriteCapacityUnits: 10
        }
    };

    try {
        await dynamoDb.createTable(params).promise();
        return { statusCode: 200, body: "Table created" };
    } catch (error) {
        return { statusCode: 500, body: error.stack };
    }
};

The PutItem operation is used to create a new item. Here's an example of how to use the PutItem operation in JavaScript:

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB({region: 'us-west-2', apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    const params = {
        TableName: "myTable",
        Key: {
            "id": { S: "123" }
        }
    };

    try {
        const result = await dynamoDB.putItem(params).promise();
        return { statusCode: 200, body: JSON.stringify(result.Item) };
    } catch (error) {
        return { statusCode: 500, body: error.stack };
    }
};

Next, let's look at how to perform a read operation on a DynamoDB table using AWS Lambda. The following example demonstrates how to retrieve an item from the "myTable" table with a primary key value of "123":

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB({region: 'us-west-2', apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    const params = {
        TableName: "myTable",
        Key: {
            "id": { S: "123" }
        }
    };

    try {
        const result = await dynamoDb.getItem(params).promise();
        return { statusCode: 200, body: JSON.stringify(result.Item) };
    } catch (error) {
        return { statusCode: 500, body: error.stack };
    }
};

To perform an update operation on a DynamoDB table, you can use the updateItem method. The following example demonstrates how to increase an item's attribute value in the "myTable" table with a primary key value of "123":

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB({region: 'us-west-2', apiVersion: '2012-08-10'});

exports.handler = async (event) => {
        const params = {
        TableName: 'myTable',
        Key: {
            primaryKey: { S: '123' }
        },
        UpdateExpression: 'SET myAttribute = myattribute + :val',
        ExpressionAttributeValues: {
            ':val': { N: '1' }
        },
        ReturnValues: 'ALL_NEW'
    };

    try {
        const result = await dynamoDB.updateItem(params).promise();
        return { statusCode: 200, body: JSON.stringify(result.Item) };
    } catch (error) {
        return { statusCode: 500, body: error.stack };
    }
};

To perform an delete operation on a DynamoDB table

const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB({region: 'us-west-2', apiVersion: '2012-08-10'});

exports.handler = async (event) => {
    const params = {
        TableName: 'myTable',
        Key: {
            primaryKey: { S: '128' }
        }
    };

    try {
        const result = await dynamoDB.deleteItem(params).promise();
        return { statusCode: 200, body: JSON.stringify(result.Item) };
    } catch (error) {
        return { statusCode: 500, body: error.stack };
    }
};

Refer to this repository for more information.