Search code examples
aws-lambdaamazon-dynamodbserverless-frameworkaws-serverless

Missing the key id, in the item [serverless framework + lambda + dynamodb]


Below is the dynamo-table.yml

Resources:
  AuctionsTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: AuctionsTable
        BillingMode: PAY_PER_REQUEST
        AttributeDefinitions:
          - AttributeName: id,
            AttributeType: S
        KeySchema:
          - AttributeName: id,
            KeyType: HASH

Below is the handler code to insert records in dynamodb.

import AWS from 'aws-sdk';
import { v4 as uuid } from 'uuid';

const dynamodb = new AWS.DynamoDB.DocumentClient();

async function createAuction(event, context) {

  const { title } = JSON.parse(event.body);
  const now = new Date();
  const params = {
    TableName: 'AuctionsTable',
    Item: {
      'id' : {S: `${uuid()}`},
      'title' : {S: `${title}`},
      'status': {S: `OPEN`},
      'createdAt': {S: now.toISOString()}
    }
  };
  console.log(`Auction: ${JSON.stringify(params)}`);
  await dynamodb.put(params).promise();
  return {
    statusCode: 201,
    body: JSON.stringify(params),
  };
}

export const handler = createAuction;

Below is the content for the serverless.yml file,

service:
  name: auction-service

plugins:
  - serverless-bundle
  - serverless-pseudo-parameters

provider:
  name: aws
  runtime: nodejs12.x
  memorySize: 128
  stage: ${opt:stage, 'dev'}
  region: ap-south-1
resources:
  - ${file(src/resources/dynamodb-table.yml)}
  - ${file(src/resources/role.yml)}

functions:
  createAuction:
    handler: src/handlers/createAuction.handler
    role: auctionServiceRole
    events:
      - http:
          method: POST
          path: /auction

custom:
  bundle:
    linting: false
  tableName: "AuctionsTables"

Problem: When I am hitting POST URL and visit CloudWatch logs, below is the error,

{
    "errorType": "ValidationException",
    "errorMessage": "One or more parameter values were invalid: Missing the key id, in the item",
    "code": "ValidationException",
    "message": "One or more parameter values were invalid: Missing the key id, in the item",
    "time": "2021-02-15T15:02:42.606Z",
    "requestId": "C344O7CTTHF3PAR1OP8BQIFBT7VV4KQNSO5AEMVJF66Q9ASUAAJG",
    "statusCode": 400,
    "retryable": false,
    "retryDelay": 8.687787589723229,
    "stack": [
        "ValidationException: One or more parameter values were invalid: Missing the key id, in the item",
        "    at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:52:27)",
        "    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)",
        "    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:78:10)",
        "    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:688:14)",
        "    at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)",
        "    at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)",
        "    at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10",
        "    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)",
        "    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:690:12)",
        "    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:116:18)"
    ]
}

also in postman, it returns status code as 502 Bad gateway,

{
    "message": "Internal server error"
} 

Question: What can be the issue? Even a small help will be really helpful. Thanks in advance.


Solution

  • I'm not sure you're using the DocumentClient API correctly. For example, you have

        Item: {
          'id' : {S: `${uuid()}`},
          'title' : {S: `${title}`},
          'status': {S: `OPEN`},
          'createdAt': {S: now.toISOString()}
        }
    

    and I've only ever used it this way:

        Item: {
          id :  uuid(),
          title : title,
          status: "OPEN",
          createdAt: now.toISOString()
        }
    

    Perhaps this is why the aws-sdk is complaining about a missing id key.