Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Hands-On Serverless Applications with Go

You're reading from   Hands-On Serverless Applications with Go Build real-world, production-ready applications with AWS Lambda

Arrow left icon
Product type Paperback
Published in Aug 2018
Publisher Packt
ISBN-13 9781789134612
Length 416 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Mohamed Labouardy Mohamed Labouardy
Author Profile Icon Mohamed Labouardy
Mohamed Labouardy
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. Go Serverless FREE CHAPTER 2. Getting Started with AWS Lambda 3. Developing a Serverless Function with Lambda 4. Setting up API Endpoints with API Gateway 5. Managing Data Persistence with DynamoDB 6. Deploying Your Serverless Application 7. Implementing a CI/CD Pipeline 8. Scaling Up Your Application 9. Building the Frontend with S3 10. Testing Your Serverless Application 11. Monitoring and Troubleshooting 12. Securing Your Serverless Application 13. Designing Cost-Effective Applications 14. Infrastructure as Code 1. Assessments 2. Other Books You May Enjoy Index

Chapter 5: Managing Data Persistence with DynamoDB


  1. Implement an update handler to update an existing movie item.

Answer: The handler expects a movie item in a JSON format; the input will be encoded to a Movie struct. The PutItem method is used to insert the movie to the table as follows:

func update(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
  var movie Movie
  err := json.Unmarshal([]byte(request.Body), &movie)
  if err != nil {
    return events.APIGatewayProxyResponse{
      StatusCode: 400,
      Body: "Invalid payload",
    }, nil
  }

  ...

  svc := dynamodb.New(cfg)
  req := svc.PutItemRequest(&dynamodb.PutItemInput{
    TableName: aws.String(os.Getenv("TABLE_NAME")),
    Item: map[string]dynamodb.AttributeValue{
      "ID": dynamodb.AttributeValue{
        S: aws.String(movie.ID),
      },
      "Name": dynamodb.AttributeValue{
        S: aws.String(movie.Name),
      },
    },
  })
  _, err = req.Send()
  if err != nil {
    return events.APIGatewayProxyResponse{
      StatusCode: http.StatusInternalServerError,
      Body: "Error while updating the movie",
    }, nil
  }

  response, err := json.Marshal(movie)
  ...

  return events.APIGatewayProxyResponse{
    StatusCode: 200,
    Body: string(response),
    Headers: map[string]string{
      "Content-Type": "application/json",
    },
  }, nil
}

  1. Create a new PUT method in API Gateway to trigger the update Lambda function.

Answer: Expose a PUT method on the /movies resource and configure the target to be the Lambda function defined earlier. The following screenshot illustrates the results:

 

  1. Implement a single Lambda function to handle all type of events (GET, POST, DELETE, PUT).Answer:
func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
 switch request.HTTPMethod {
 case http.MethodGet:
 // get all movies handler
 break
 case http.MethodPost:
 // insert movie handler
 break
 case http.MethodDelete:
 // delete movie handler
 break
 case http.MethodPut:
 // update movie handler
 break
 default:
 return events.APIGatewayProxyResponse{
 StatusCode: http.StatusMethodNotAllowed,
 Body: "Unsupported HTTP method",
 }, nil
 }
}
  1. Update the findOne handler to return a proper response code for a valid request but an empty data (for example, no movie for the ID requested).

Answer: When handling input of a user (movie ID in our case), validation is mandatory. Hence, you need to write a regular expression to ensure the ID given in parameter is properly formed. The following are examples of regular expressions to validate an ID:

    • Pattern for alphanumeric ID: [a-zA-Z0-9]+
    • Pattern for digits only ID: [0-9]+
  1. Implement a pagination system on the findAll endpoint using a Range header and using a Query string.

Answer: Use the Limit option in the ScanRequest method to limit number of returned items:

dynamodbClient := dynamodb.New(cfg)
req := dynamodbClient.ScanRequest(&dynamodb.ScanInput{
    TableName: aws.String(os.Getenv("TABLE_NAME")),
    Limit: aws.Int64(int64(size)),
})

The number of items to return can be read from the request headers:

size, err := strconv.Atoi(request.Headers["Size"])
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images