Developers , Javascript

AWS λ + Serverless framework and DynamoDB

How about using the Lambda function and not worrying too much about availability with guaranteed execution and direct access to DynamoDB? The purpose of this article is to show you in a simple way how to create a serverless lambda function with direct access to DynamoDB. I assume that you already have knowledge of JavaScript, ...

How about using the Lambda function and not worrying too much about availability with guaranteed execution and direct access to DynamoDB?

The purpose of this article is to show you in a simple way how to create a serverless lambda function with direct access to DynamoDB.

I assume that you already have knowledge of JavaScript, AWS, Lambda concept and Serverless framework. Ok?

Let’s start!

Let’s create a simple function that performs a query on the DynamoDB database. See the example code below:

index.js

JavaScript
"use strict"

const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
const ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

const params = {
  ExpressionAttributeValues: {    
    ':id': '67554837_xxx',
  },
  KeyConditionExpression: 'Id = :id',
  ProjectionExpression: 'Id, createdAt',
  TableName: 'Table_Name',
};

exports.handle = async function(event, context, callback) {
  try {  
    const dyn = await ddb.query(params, (err, data) => {
      if (err) {
        console.error('Error', JSON.stringify(err, null, 2));
      } else {
        console.log('Success');
        data.Items.forEach((item) => {
          console.log('item:', item);
        });        
      }
    }).promise();

    return dyn;
  } catch (e) {
    console.log(e);
    return e
  } 
}

Let’s go to the serverless configuration now.

In the serverless.yml file we will configure the following:

What’s inside the custom key are variables that are declared. It’s a place to declare different types of variables.

Serverless has plugins that are community created extensions to what it can do.

In this case we are using some plugins, and specifically the serverless-domain-manager plugin requires some variables declared inside the custom to know how to make the correct DNS annotations (for friendly DNS terms to connect to the API Gateway it creates).

To access other AWS services, another plugin is used, which is serverless-iam-roles-per-function. Which allows Serverless to interpret these settings correctly:

See full serverless.yml file below:

JavaScript
"use strict"

const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
const ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

const params = {
  ExpressionAttributeValues: {    
    ':id': '67554837_xxx',
  },
  KeyConditionExpression: 'Id = :id',
  ProjectionExpression: 'Id, createdAt',
  TableName: 'Table_Name',
};

exports.handle = async function(event, context, callback) {
  try {  
    const dyn = await ddb.query(params, (err, data) => {
      if (err) {
        console.error('Error', JSON.stringify(err, null, 2));
      } else {
        console.log('Success');
        data.Items.forEach((item) => {
          console.log('item:', item);
        });        
      }
    }).promise();

    return dyn;
  } catch (e) {
    console.log(e);
    return e
  } 
}

Deploy your function

There are some efficient ways to deploy the function. Via command line or using AWS Serverless CI/CD to automate the deployment process in a production environment, for example.Command line

.
$ serverless deploy

For more details and other command execution options, take a look at the serverless doc: https://www.serverless.com/framework/docs/providers/aws/cli-reference/deploy

For a production environment, look at this AWS dochttps://aws.amazon.com/quickstart/architecture/serverless-cicd-for-enterprise/

Related Articles

Developers Engineer Write Up

Deploying NestJS Microservices to AWS ECS with Pulumi IaC

Let’s see how we can deploy NestJS microservices with multiple environments to ECS using...

Read more
CI/CD
Developers DevOps

What is CI/CD? A Guide to Continuous Integration & Continuous Delivery

Learn how CI/CD can improve code quality, enhance collaboration, and accelerate time-to-ma...

Read more
AI Developers Engineer Write Up

Build a Powerful Q&A Bot with LLama3, LangChain & Supabase (Local Setup)

Harness the power of LLama3 with LangChain & Supabase to create a smart Q&A bot. This guid...

Read more
Demystifying AI
AI Developers

Demystifying AI: The Power of Simplification

Unleash AI's power without the hassle. Learn how to simplify complex AI tasks through easy...

Read more