0
votes

I'm using serverless framework to code AWS lambda function. I need to get a form data from a HTML page and save it to Dynamodb using AWS lambda. So i have written the code in nodejs and API endpoints as well. Finally i deployed the application to AWS. So when i'm trying to post data using both CURL and Postman, it shows an "Internal Server Error"

Following are the relevant code snippets.

handler.js

const params = {
    TableName: process.env.DYNAMODB_TABLE,
    Item: {
      id: uuid.v1(),
      name: data.name,
      phone: data.phone,
      checked: false,
      createdAt: timestamp,
      updatedAt: timestamp,
    },
  };

serverless.yml

provider:
  name: aws
  runtime: nodejs6.10
  environment:
    DYNAMODB_TABLE: ${self:service}-${opt:stage, self:provider.stage}
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"

I'm not sure where to define the Dynamo table name and whether it is created by while running the code by automatically? And i followed this github repo - https://github.com/serverless/examples/tree/master/aws-node-rest-api-with-dynamodb

1
What's the error that shows up on CloudWatch? - Noel Llevares
The error is probably because you haven't created the DynamoDB table. - Noel Llevares

1 Answers

0
votes

Your current serverless.yml does not define and create the DynamoDB table for you.

You can do it by defining it in the resources section of your serverless config.

provider:
  name: aws
  runtime: nodejs6.10
  environment:
    DYNAMODB_TABLE: ${self:service}-${opt:stage, self:provider.stage}-phones
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: arn:aws:dynamodb:*:*:*


resources:
  Resources:
    phonesTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: ${self:service}-${opt:stage, self:provider.stage}-phones
        AttributeDefinitions:
          - AttributeName: id
            AttributeType: S
        KeySchema:
          - AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1

Reference: https://serverless.com/framework/docs/providers/aws/guide/resources/