Need a cloud database for your Vue app?

  • by

Using AWS DynamoDB in your Vue apps

DynamoDB: Your cloud database

Have you checked out Amazon Web Services DynamoDB database?

DynamoDB is a powerful database that can be used to store complex data as key-value pairs with single-digit millisecond performance!

Get more information on DynamoDB at the official Amazon Web Services site https://aws.amazon.com/DynamoDB/

Your Vue app and DynamoDB tutorial

In this tutorial I will show you how easy it is to use AWS DynamoDB in your Vue apps to save your data in the cloud.

I will show you how to add a simple item composed of a name and telephone number to a DynamoDB table (in this tutorial, I’ll interchange table with database but essentially they are the same). I’ll also show you how to update, get and delete the item.

Our simple tutorial has a number of buttons to access our database

You save your data in a DynamoDB table as key-value pairs. The types of data that you can save are listed in the image below:

These are the value types that you can save in a DynamoDB database

First things first

There are a few things that you need to take care of before you can access an AWS DynamoDB table.

You’ll need to install the AWS-SDK dependency

You can install it by using the following in your terminal window:

Install the dependency using npm install aws-sdk in your terminal

Or you can install it via the Dependencies dashboard if you’re using Vue CLI 3.0

Install the aws-sdk via the Vue CLI Dependencies dashboard

You’ll need an AWS account

Sign up for an AWS account if you don’t already have one. There’s a free tier option which means that you can try most of AWS’s services for free for a year. The costs are pretty low even out of the free tier as you only pay for what you use.

You’ll need a DynamoDB table

A DynamoDB table is where you store your data. Think of a table as your database. You create a table, either in code, via the AWS CLI or at the AWS console.

Creating a table in the AWS console

Here’s how to do it in the console. Login to your account, open up the console and select Services from the menu (top-left). Then search for and open up DynamoDB. Now select Create table and enter TestDynamo as the table name and phone as the Primary key. Leave String as the attribute value type for the primary key. The primary key has to be unique for the table.

Check out this quick video tutorial on how to create a DynamoDB table.

You’ll need credentials

You need credentials to use any of AWS’s services such as DynamoDB. You can get credentials via AWS’s Cognito service by using your own sign in system, Cognito, Facebook, Google or others. You can also access the AWS services as a guest or unauthorised user which means that you don’t have to sign in but you still need credentials. It’s easy to get temporary credentials without having to sign in.

By using an Identity Pool, AWS will issue you temporary credentials which you can then use to access your DynamoDB table.

You’ll need a Cognito Identity Pool

So you’ll need to have an identity pool in order to get temporary credentials. Here’s a video showing how to create an identity pool if you’re interested, Creating an Identity Pool

You’ll need permission

AWS has a number of security measures. The first is the requirement for credentials to access any of AWS’s services. Another safeguard is permission policies. Permission policies are statements which define who can do what with what resource. You then attach the policy to your resources or users.

In our case we need a policy allowing unauthenticated users to interact with our DynamoDB table.

A permissions policy is simply a JSON object, here’s what our policy looks like:

Our IAM permissions policy allowing us to transact with our dynamoDB table

Most policies have the following elements:

  • Effect – can be Deny or Allow
  • Action – what are you allowing or denying. In our case we’re allowing:
    • PutItem
    • GetItem
    • DeleteItem
    • UpdateItem
  • Resource – the AWS resource that you’re reacting with, in our case, our DynamoDB table

When you created your Identity Pool, you should have ticked the box to enable access to unauthenticated identities. This would have created an unauthenticated role for you. You can also edit your Identity Pool and create a new role for unauthenticated users.

We’re going to attach our permission policy to the unauthenticated role, giving it permission to put, get, delete and update items in our DynamoDB table.

IAM roles

Once you have an unauthenticated role, open up the IAM service in your AWS console. Select Roles from the left menu and select your unauthenticated role. Select the attached policy. There may be more than one policy depending on whether or not you have previously attached policies to this role. You can either edit the existing policy or create a new one. In either case, make sure that your policy includes this policy statement:

Required permissions policy statement to transact with our dynamoDB table

This policy gives the unauthenticated role permission to put, get, delete and update items in our DynamoDB table.

You’ll have to change the Resource to your DynamoDB table ARN (Amazon resource name) which you’ll find if you open your table up in the AWS console and select the Overview tab. You’ll find the ARN at the bottom.

Now that we have the preparations complete, let’s have a look at our app.

You can check out a quick video tutorial on how to do this.

Let’s look at our Vue app and DynamoDB tutorial

We have four buttons, each triggering a method when clicked:

  • Add item to table – triggers addItem() – adds an item to our table
  • Delete item – triggers deleteItem() – deletes an item in the table
  • Get item out table – triggers getItem() – fetches an item out the table and prints the result in the console
  • Update item – triggers updateItem() – updates an item in the table

The code

I have one page, a view and in its <script> tags, I include the following:

Require the sdk, set your region and identity pool id

Here we get an instance of an AWS object so we can access the SDK. Then we configure our AWS object to include our Identity Pools’ ID as well as its region.

I also have one prop, credentials:

Our credentials prop contains the latest credentials issued by AWS

We can access the credentials prop anywhere in this view.

Getting credentials

As mentioned above, we need credentials to access the AWS DynamoDB database. Our Identity Pool allows us to get temporary credentials without having to sign in. Here’s the code we use to get the temporary credentials:

Gets the temporary credentials to access AWS’s dynamoDB table

We call our GetCredentials() method in our views’ created method. The result is an object containing our security credentials which we can then use to access our DynamoDB table.  The credentials object contains:

  • accessKeyId
  • secretAccessKey
  • sessionToken

You can read more about the credentials here https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html

The getPromise() returns a “thenable” promise. It gets the existing credentials, refreshing them if they are not yet loaded or have expired. We return the credentials and assign them to our credentials prop which we can use later.

Note that I return null if there is an error. You should handle the error according to your wishes.

Our methods that interact with our DynamoDB table

Here are our four methods:

  • addItem()
  • deleteItem()
  • updateItem()
  • getItem()

They are all basically structured the same and use the same code. Ill cover the addItem() method in detail and then briefly cover the others.

The addItem() method

We use this method to add an item to our DynamoDB table.

Here’s the first bit of code:

The first bit of addItem() code

We create a DocumentClient object which makes it easy interacting with our table as it allows us to input our data as native JavaScript types. The response is also converted into native JavaScript types.

You can get more detailed information on the available methods for the DocumentClient here https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html

We then create a parameters object, supplying our table name and the item details. You must supply an unique primary key and value. In our case, our primary key is our phone attribute.

Next, we use an if statement to check whether we have credentials and if we do, we go ahead and call the put() method to add our item to our table. Here’s the code:

The DocumentClient’s put() method adds an item to our dynamoDB table

The put() method creates a new item or replaces an old item with the new item. It returns an error object on failure or a data object on success. You can set the ReturnValues parameter to either ALL_OLD in which case it returns the old attributes values if they were overwritten or NONE which returns an empty object (the default).

If we don’t have credentials then the else statement is executed. Here’s the code for that:

We use the getPromise() method to get the latest temporary credentials

Here we call the getPromise() method to get the credentials.

If we’re successful, then we update our credentials prop and then proceed to add our item to our table by calling put().

If we fail to get credentials then we set our credentials prop to null. We can’t add our item to our table as we cannot interact with our DynamoDB table without credentials.

Our other methods

Our remaining methods:

  • deleteItem()
  • updateItem()
  • getItem()

These methods follow the same structure as the addItem() method. Which is:

  • get a DocumentClient instance
  • set up our parameters containing the table name and primary key plus our items’ data
  • use an if/else statement to check if we already have credentials
  • if we have credentials then we proceed to execute our transaction
  • if we don’t have credentials then we first get them and then:
    • if we’re successful then we execute our transaction
    • if we’re not, then we can’t transact with our table

the deleteItem() method

This method deletes an item from the DynamoDB table.

First get an instance of the DocumentClient and then set up your parameters like this:

Our delete parameters

This will delete the item identified by the primary key, phone which in this case is the item with the phone number of 123456789.

Then use the if/else statement as described above to call the DocumentClient delete() method:

Pass your parameters to the DocumentClient delete() method

The delete() method deletes a single item identified by the primary key.

It returns an error on failure or a data object if successful. You can set the ReturnValues parameter to ALL_OLD in which case it returns an object containing the deleted attributes and their values or NONE where it returns an empty object (the default).

The updateItem() method

This method updates an existing item or adds a new item if it does not exist.

First get an instance of the DocumentClient and then set up your parameters like this:

Our update item parameters

The primary key, phone identifies the item that we want to update.

The UpdateExpression states that we want to set the attribute named #n to the value : x. we then set #n’s value in ExpressionAttributeNames and its value : x in ExpressionAttributeValues.

You can get more information on using Update Expressions in DynamoDB here https://docs.aws.amazon.com/amazonDynamoDB/latest/developerguide/Expressions.UpdateExpressions.html

Finally we set the ReturnValues, the values that we want returned on success of the update, to ALL_NEW. See the documentation https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html for other values that you might want returned.

We then use the if/else statement as described above to call the DocumentClient update() method:

Our DocumentClient update() method

The update() method edits an existing item’s attributes or adds a new item if the item does not exist.

It returns an error object on failure else it returns a data object. You can set the ReturnValues parameter to:

  • NONE – returns an empty object
  • ALL_OLD – returns all the old attributes and their values, prior to the update
  • UPDATED_OLD – returns the old attributes and values which have since been updated
  • ALL_NEW – returns all the attributes and values after being updated
  • UPDATED_NEW – returns the attributes and values that have been updated

Here’s the result of our update:

The result of our update

The getItem() method

First get an instance of the DocumentClient and then set up your parameters like this:

Our parameters for getting an item out our dynamoDB table

Again, the primary key, phone, identifies the item that we want to get.

Then use the if/else statement as described above to call the DocumentClient get() method:

The get() method returns an error object if there’s an error. On success, it returns the requested items’ attributes or null if there is an error. It will return an empty object if the item does not exist.

Here’s the result for our get item:

The result of getting an item out of our dynamoDB table

I hope that you found this tutorial useful.

Get the code as PDF

Check out the Youtube version of this tutorial.