DEV Community

Cover image for Getting started with Lambda + DynamoDB Using Serverless Framework
Oryam
Oryam

Posted on • Edited on

Getting started with Lambda + DynamoDB Using Serverless Framework

TOC

Part 1 : Intro to AWS
Part 2 : Getting started with Serverless FrameWork
Part 3 : Create a Lambda Function
Part 4 : Create a DynamoDB Data-base
Part 5 : Connect the Lambda to DynamoDB
Resources

Part 1:

Intro to AWS (Lambda-functions and DynamoDB)

What is Serverless?

Serverless !== No Server.
It means that you as a developer don't need to worry about writing, deploying and maintaining the server behind the scenes. So you can focus on writing the actual functionality of the server.

Why serverless?

A serverless service can scale depending on its use. Scale up when using and scale down when not.
Some use case examples: voting tv shows or delivery apps on special holidays. Both need to scale up/down for a short time.
Pros: low cost and easy to scale
Cons: cold-start can happen, don't have access to a file system (no state in memory), each function needs to be independent.

Why AWS?

Easy to get started with, popular and free for prototype scale, but you can choose any other cloud service you want, they all have kind of the same services.

Part 2:

Getting started with Serverless FrameWork (how to setup a new profile)

  • You can also use the GUI on AWS website which can be easier at first, but if you want to keep, change or duplicate your settings and functions it is preferred to work with serverless.

The serverless framework helps us to setup and deploy all the services from the cloud using a yml file and a CLI.

You can use the steps here but it’s also recommended to use the serverless docs

First steps:

  1. Create a new user on AWS IAM service with administrator access and keep the user keys.
  2. Install the serverless framework using npm install -g serverless
  3. Config your profile using
serverless config credentials --provider aws --key <your key> --secret <your secret key> --profile <choose profile name> 
Enter fullscreen mode Exit fullscreen mode

Now you all setup and can start using serverless with AWS.

Part 3:

Create a Lambda Function

Go to a new folder and run:

serverless create --template aws-nodejs --path <folder name> 
Enter fullscreen mode Exit fullscreen mode

Now inside the path you entered you'll have handler.js and serverless.yml files.
The yml file should look like: (without the comments)

service: <your path>
frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x

functions:
  hello:
    handler: handler.hello
Enter fullscreen mode Exit fullscreen mode

In this file we need to add the serverless profile from the last part.
So in the provider section below runtime enter your profile name like this:

provider:
  name: aws
  runtime: nodejs12.x
  profile: <your profile name>
Enter fullscreen mode Exit fullscreen mode

Now if you run serverless deploy
Serverless will create a config file and deploy the project with the hello function to AWS.
If you check AWS lambda with your account you will see the new function.

Part 4:

Create a DynamoDB Data-base

DynamoDB is a database service from AWS that will scale automatically with the data you will put on it so you don't have to manage a database system.

First you need to add dynamodb as a resource in the yml file.

  • in yml file the lining is important !
custom:
  usersTable: usersTable

resources:
  Resources:
    DynamoDBTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:custom.usersTable}
        AttributeDefinitions:
          - AttributeName: id
            AttributeType: S
        KeySchema:
          - AttributeName: id
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
        StreamSpecification:
          StreamViewType: NEW_IMAGE   
Enter fullscreen mode Exit fullscreen mode

We used custom variables for the table name so we can use it later in other places.

After saving the changes you can run serverless deploy and check
that it was created on your AWS account.

Part 5:

Connect the Lambda to DynamoDB

  • To keep things simple and easy we will only create a user (put). We now will change the hello function to a create-user function by this steps:

1.Import AWS library with require the sdk

const AWS = require('aws-sdk');
Enter fullscreen mode Exit fullscreen mode

2.Change function name to handler instead hello (yml and js)
3.Create a Dynamo document-client

const documentClient = new AWS.DynamoDB.DocumentClient();
Enter fullscreen mode Exit fullscreen mode

4.Create AWS params

const params = {
    TableName: 'usersTable',
    Item: {
      id: '001',
      name: 'john',
    },
  };
Enter fullscreen mode Exit fullscreen mode

5.Because it's an async function we can use try/catch to assign the user to the client-document with the put method.

try {
    const data = await documentClient.put(params).promise(); //aws promise
    responseBody = JSON.stringify(data);
    statusCode = 201; //object created
  } catch (err) {
    responseBody = `unable to create user - ${err}`;
    statusCode = 403;
  }
Enter fullscreen mode Exit fullscreen mode

final result:

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

module.exports.handler = async (event, context) => {
  console.log('event', event);
  const documentClient = new AWS.DynamoDB.DocumentClient();
  let responseBody = '';
  let statusCode = 0;

  //AWS params
  const params = {
    TableName: 'usersTable',
    Item: {
      id: '001',
      name: 'john',
    },
  };

  try {
    const data = await documentClient.put(params).promise(); //aws promise
    responseBody = JSON.stringify(data);
    statusCode = 201; //object created
  } catch (err) {
    responseBody = `unable to create user - ${err}`;
    statusCode = 403;
  }

  const response = {
    statusCode,
    headers: { 'Content-Type': 'application/json' },
    body: responseBody,
  };

  return response;
};
Enter fullscreen mode Exit fullscreen mode

As you probably see the user data is hard coded. To enter variables you need to use API Gateway.
After saving the file you can deploy it with serverless deploy
And test the Lambda function on AWS, then check DynamoDB to see the new user.

Hope it was helpfull πŸ‘©β€πŸ’»

Resources:

  • A great video series by Sam from Complete Coding Link
  • A tutorial about how to make it all using the AWS GUI Link
  • Serverless Framework docs Link

Top comments (0)