Serverless Backend using AWS Lambda: Hands-on Guide

0
9


Storing Data in DynamoDB

Before we can start storing data in our DynamoDB, we need to set some permissions for the Lambda function to have write access.

Inside the serverless.yml file, remove the contents of the functions section completely and create a new function called createHero as shown below:

functions:
  createHero:
    handler: create.run
      events:
        - http:
            path: heroes
            method: post

But the Lambda function does not have the permissions to interact with our DynamoDB table by default. So we need to give these permissions to our Lambda function. This can be done with the help of iamRole.

The serverless framework already uses iamRole under the hood. We need to use iamRoleStatements to extend the permissions for the specific iamRole.

In your DynamoDB console, click on the table to open its overview. In the Table Details section, you should find the Amazon Resourse Name (ARN). Enter its content as Resource inside the iamRoleStatements in the serverless.yml file as shown below:

provider:
  name: aws
  runtime: nodejs8.10
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:PutItem
      Resource: "<enter your Amazon Resource Name here>"

We also have to create the function that will actually send the data to our DynamoDB table. So create a new file named create.js.

$ touch create.js

Inside this file, add a function that will return a response.

module.exports.run = async (event) => {
  const data = JSON.parse(event.body);
  return {
    statusCode: 200,
    body: JSON.stringify(data)
  };
};

To let this function interact with DynamoDB, we need to import the aws-sdkand instantiate a documentClient() inside the serverless.yml file:

const AWS = require("aws-sdk");
const client = new AWS.DynamoDB.documentClient();

Along with this, create a new const named params as shown below:

module.exports.run = async (event) => {
  const data = JSON.parse(event.body);
  const params = {
    TableName: "heroes",
    Item: {
      id: "hero1",
      name: data.name,
      checked: false
    }
  };
  await client.put(params).promise();
  return {
    statusCode: 200,
    body: JSON.stringify(data)
  };
};

There is one issue in this code, every new item that we add to our table will have the same id. To solve this, we can add the uuid package to our code. This package will generate a new id for every new request.

Create a new file named package.json:

$ touch package.json

Inside this file, write the following code:

{
  "name": "less-app",
  "private": true
}

Then install the uuid package using NPM/Yarn:

$ npm install --save uuid

Finally, import this package into the create.js file:

const uuid = require("uuid/v4");

Also re-write the id property inside the Item object using the uuid package as shown here:

Item: {
  id: uuid(),
  name: data.name,
  checked: false
}

With that, we have set up everything and can redeploy this using serverless.

$ sls deploy

Once deployed we can use curl to create an entry into the DynamoDB table as shown below:

$ curl -X "<POST URL>" --data '{"text": "batman"}'

Check in the AWS console to see if this submission was recorded.



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here