How to connect to Dynamo DB and do CRUD operations in AWS Serverless ?

To connect to DynamoDB in the AWS Serverless Framework, you will need to do the following:

  1. Install the AWS SDK:

The AWS SDK for JavaScript is a collection of libraries that allows you to interact with AWS services from your Node.js code. To install the AWS SDK, navigate to the root directory of your serverless application and run the following command:

npm install aws-sdk
  1. Configure the SDK:

Before you can use the AWS SDK to connect to DynamoDB, you will need to configure it with your AWS access keys. You can do this by calling the AWS.config.update method and passing in your access key and secret key. Here’s an example of how you might configure the SDK in your code.

const AWS = require('aws-sdk');

AWS.config.update({
  region: 'us-east-1',
  accessKeyId: 'YOUR_ACCESS_KEY',
  secretAccessKey: 'YOUR_SECRET_KEY',
});

Replace YOUR_ACCESS_KEY and YOUR_SECRET_KEY with your actual AWS access key and secret key, respectively. If you have already configured AWS credentials you can skip this step.

  1. Create a DynamoDB client:

To create a DynamoDB client, you can use the DynamoDB.DocumentClient constructor from the AWS SDK. Here’s an example of how you might create a client in your code:

const dynamoDb = new AWS.DynamoDB.DocumentClient();
  1. Use the client to interact with DynamoDB:

Once you have a DynamoDB client, you can use it to perform various operations on your DynamoDB tables. Here are a few examples of how you might use the client:

  • To create a new item in a table:
const params = {
  TableName: 'my-table',
  Item: {
    id: 1,
    name: 'John Smith',
  },
};

dynamoDb.put(params, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Item added to table');
  }
});
  • To retrieve an item from a table:
const params = {
  TableName: 'my-table',
  Key: {
    id: 1,
  },
};

dynamoDb.get(params, (error, result) => {
  if (error) {
    console.error(error);
  } else {
    console.log(result.Item);
  }
});
  • To update an existing item in a table:
const params = {
  TableName: 'my-table',
  Key: {
    id: 1,
  },
  UpdateExpression: 'SET #name = :name',
  ExpressionAttributeNames: {
    '#name': 'name',
  },
  ExpressionAttributeValues: {
    ':name': 'Jane Smith',
  },
};

dynamoDb.update(params, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Item updated');
  }
});
  • To delete an item from a table:
const params = {
  TableName: 'my-table',
  Key: {
    id: 1,
  },
};

dynamoDb.delete(params, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Item deleted');
  }
});
  • To scan a table and return all items:
const params = {
  TableName: 'my-table',
};

dynamoDb.scan(params, (error, result) => {
  if (error) {
    console.error(error);
  } else {
    console.log(result.Items);
  }
});
  • To query a table using a secondary index:

onst params = {
  TableName: 'my-table',
  IndexName: 'name-index',
  KeyConditionExpression: '#name = :name',
  ExpressionAttributeNames: {
    '#name': 'name',
  },
  ExpressionAttributeValues: {
    ':name': 'John Smith',
  },
};

dynamoDb.query(params, (error, result) => {
  if (error) {
    console.error(error);
  } else {
    console.log(result.Items);
  }
});

The above examples use callbacks to retrieve the result. It retrieves the results asynchronously.

Instead you can use the below code and convert the result to promises and then get back the results synchronously using await keyword:

Retrieving an item:

const params = {
  TableName: TABLE_NAME,
  Key: {
    [PRIMARY_KEY]: '123'
  }
};

const result = await dynamoDb.get(params).promise();
const item = result.Item;

The promise() method converts the result to a promise and then you can use await keyword to get the result back synchronously.

Adding an item:

const item = {
  [PRIMARY_KEY]: '456',
  name: 'John Smith',
  age: 30
};

const params = {
  TableName: TABLE_NAME,
  Item: item
};

await dynamoDb.put(params).promise();

Similarly for other operations.

That’s it!


Posted

in

, ,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading