Lambda Function (Part 3)
Tags: beginners, cloud, serverless, aws
Published: 2023-10-18 14:33:48


#### -------------- See part 2 from [here ](https://dev.to/aws-builders/lambda-function-part-2-2pl4)----------------

# Creating Conditional Step Type

### Introduction
In the other branch of the parallel task, you need to update the DynamoDB tables.

In many scenarios, the flow is dependent upon a choice. In order to fulfill this requirement, AWS Step Functions provides a Choice step.

The second branch starts with the UpdateDB task and its type is choice. This means that when the flow arrives here, a choice has to be made, and it is up to AWS Step Functions to make that choice. The next step that gets executed is based on the choice.

In the Choices field on line 6, you would typically declare a series of comparisons. In this case, there are only two possibilities so there would need to be one comparison declared, using the Default field that explains which task to run in case no condition is satisfied. The conditional step template is shown below. Note: remember that this is just part of the larger JSON template.

```
{
    "StartAt": "UpdateDB",
    "States": {
        "UpdateDB": {
            "Type": "Choice",
            "Choices": [{
                "Variable": "$.level",
                "StringEquals": "latest",
                "Next": "Last Level"
            }],
            "Default": "Simple Level"
        },
        "Last Level": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:EndsLastLevel",
            "End": true
        },
        "Simple Level": {
            "Type": "Task",
            "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:EndsSimpleLevel",
            "End": true
        }
    }
}
```

A choice is made up of at least three fields:

Variable: The variable that needs to be evaluated, defined using JMESpath
- Kind of comparison: AWS provides different kinds of comparisons, based on the type of the variable
- Next: The name of the task that will be executed in case the comparison result is true
- Note: Remember that only the first evaluation that is true is going to be executed.

In this case, $.level variable is evaluated. With the comparison StringEquals you check if its value is "latest". In this case, the Last Level task will be executed, otherwise, the Simple Level will be excecuted instead.

AWS Step Functions handles this flow efficiently by only requiring it declared in the template, such that no additional code or Lambda function is required.

There are many more kinds of comparisons available that are self-explanatory. For example:

String comparisons:

StringEquals
StringLessThan
StringGreaterThan
StringLessThanEquals
StringGreaterThanEquals

`Number comparisons:`

NumericEquals
NumericLessThan
NumericGreaterThan
NumericLessThanEquals
NumericGreaterThanEquals

`Boolean comparisons:` BooleanEquals.

And arguably the most powerful: `Timestamp conditions:`

TimestampEquals
TimestampLessThan
TimestampGreaterThan
TimestampLessThanEquals
TimestampGreaterThanEquals

In addition, for more structured and complex conditions, you can use the boolean operators like And, Or, and Not as well.

Now you have to implement functions to handle database updates. To create a completely serverless architecture, you will use DynamoDB to store your information.

In this step you are going to create two Lambda functions:
- EndsSimpleLevel: This function will be called when the user ends a simple level, not the latest level
- EndsLastLevel: This function will be called when the user completes the last level
 

**Instructions**
1. In the AWS Management Console search bar, enter Lambda, and click the Lambda result under Services:

2. Click on _Create function_.

3. Check Author from scratch and fill all fields as given below:

- Function name: _EndsSimpleLevel_
- Runtime: _Python 3.7_
 
4. Toggle the drop-down Change default execution role and fill all fields as given below:

Select the role or create your own
 
5. Click _Create function_.

6. Move into the Code source section and double-click _lambda_function.py_, replacing the contents with the code below

```
import time
import boto3
dynamodb_client = boto3.client('dynamodb')
table_name = 'CompletedLevel'
def lambda_handler(event, context):
    user_id = event.get('user_id')
    level = event.get('level')
    update_params = {
        "TableName": table_name,
        "Key": {
            "user_id": {
                "S": user_id
            }
        },
        "AttributeUpdates": {
            "last_level": {
                "Value": {
                    "S": level
                },
                "Action": "PUT"
            },
            "timestamp": {
                "Value": {
                    "S": str(time.time())
                },
                "Action": "PUT"
            }
        }
    }
    dynamodb_client.update_item(**update_params)
    return event
```

As you can see, the code is pretty simple. It calls the update_item API on the CompletedLevel table and terminates the function returning the event received. As mentioned before, the result of each function is very important because it's either what the next function will receive at the start of its flow, or the result of the entire execution.

7. To deploy your function, click _Deploy_.

You should now have two Lambda functions created for this lab. Now you will create the third and final Lambda function.

8. Navigate back to the Lambda console. In the AWS Management Console search bar, enter Lambda, and click the Lambda result under Services:

9. Click on _Create function_.

10. Check Author from scratch and fill all fields as given below:

Function name: _EndsLastLevel_
Runtime: _Python 3.7_

11. Toggle the drop-down Change default execution role and fill all fields as given below:

Select the role or create your own

12. Click _Create function_.

13. Move into the Code source section and double-click _lambda_function.py_, replacing the contents with the code below:

```
import boto3
import time
table_name = 'CompletedGame'
dynamodb_client = boto3.client('dynamodb')
def lambda_handler(event, context):
    user_id = event.get('user_id')
    total_score = event.get('total_score')
    put_params = {
        "TableName": table_name,
        "Item": {
            "user_id": {
                "S": user_id
            },
            "completed": {
                "BOOL": True
            },
            "timestamp": {
                "S": str(time.time())
            },
            "total_score": {
                "N": str(total_score)
            }
        }
    }
    dynamodb_client.put_item(**put_params)
    return event
```

This code is quite simple too. It calls the DynamoDB put_item API on the other table (CompleteLevel) and terminates returning the event received.

14. To deploy your function, click _Deploy_.

In the next step, you will create the last task that completes your flow.


# Logging Results to CloudWatch
**See the final part (part 4) from [here](https://dev.to/aws-builders/lambda-function-part-4-final-part-1c69)**


[GitHub](https://github.com/a00ayad00)
[LinkedIn](https://www.linkedin.com/in/a00ayad00)
[Facebook](https://m.facebook.com/a00ayad00)
[Medium](https://a00ayad00.medium.com/)