Getting started with Lambda + DynamoDB Using Serverless Framework
Tags: aws, serverless, node
Published: 2020-10-29 18:05:46

#### TOC
[Part 1](#part-1) : Intro to AWS 
[Part 2](#part-2) : Getting started with Serverless FrameWork
[Part 3](#part-3) : Create a Lambda Function
[Part 4](#part-4) : Create a DynamoDB Data-base
[Part 5](#part-5) : Connect the Lambda to DynamoDB
[Resources](#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](https://www.serverless.com/framework/docs/providers/aws/guide/credentials/) 

First steps:
1. Create a new user on [AWS IAM service](https://aws.amazon.com/iam/) with administrator access and keep the user keys.
2. Install the serverless framework using `npm install -g serverless`
3. Config your profile using 
```bash
serverless config credentials --provider aws --key <your key> --secret <your secret key> --profile <choose profile name> 
```
Now you all setup and can start using serverless with AWS.

###Part 3:
### Create a Lambda Function

Go to a new folder and run: 
```bash
serverless create --template aws-nodejs --path <folder name> 
```
Now inside the path you entered you'll have `handler.js` and `serverless.yml`  files.
The yml file should look like: (without the comments)
```yml
service: <your path>
frameworkVersion: '2'
 
provider:
  name: aws
  runtime: nodejs12.x
 
functions:
  hello:
    handler: handler.hello
``` 
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:
```yml
provider:
  name: aws
  runtime: nodejs12.x
  profile: <your profile name>
```
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 !
```yml
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   
```

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
```javascript
const AWS = require('aws-sdk');
```
2.Change function name to handler instead hello (yml and js)
3.Create a Dynamo document-client
```javascript
const documentClient = new AWS.DynamoDB.DocumentClient();
```
4.Create AWS params
```javascript
const params = {
    TableName: 'usersTable',
    Item: {
      id: '001',
      name: 'john',
    },
  };
```
5.Because it's an async function we can use try/catch to assign the user to the client-document with the put method.
```javascript
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;
  }
```
final result:
```javascript
'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;
};
```


As you probably see the user data is hard coded. To enter variables you need to use [API Gateway](https://aws.amazon.com/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](https://www.youtube.com/playlist?list=PLmexTtcbIn_gP8bpsUsHfv-58KsKPsGEo)
* A tutorial about how to make it all using the AWS GUI [Link](https://youtu.be/VGerk8hrP9U)
* Serverless Framework docs [Link](https://www.serverless.com/framework/docs/getting-started/)