Search code examples
amazon-web-servicesexpressaws-lambdaamazon-dynamodbserverless-framework

502 Bad Gateway Error on Serverless Framework Express Rest-API


I am trying to build a express rest-api with the serverless framework with the following code. I have a working POST request method to the path /fruits but the following GET request method throws a 502 Bad Gateway error.

const serverless = require('serverless-http');
const express = require('express');
const app = express();
const AWS = require('aws-sdk');

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

app.get('/fruits/:fruitName', (req, res) => {
    const params = {
        TableName: TABLE_NAME,
        Key: {
            fruitName: req.params.fruitName,
        },
    }
    dynamoDB.get(params, (err, res) => {
        if (err) {
            console.log(error);
            res.status(400).json({ error: 'Could not get fruit' });
        }
        if (res.Item) {
            const { fruitName, biName} = res.Item;
            res.json({ fruitName, biName});
        } else {
            res.status(404).json({ error: "Fruit not found" });
        }
    })
})

...

module.exports.handler = serverless(app);

I have set up a serverless.yml as follows

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: us-west-2
  iamRoleStatements:
    - Effect: 'Allow'
      Action:
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: 
        - { "Fn::GetAtt": ["FruitsTable", "Arn" ] }
  environment:
    TABLE_NAME: 'fruits'

resources:
  Resources:
    FruitsTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          - AttributeName: fruitName
            AttributeType: S
        KeySchema:
          - AttributeName: fruitName
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: 'fruits'
 
functions:
  app:
    handler: index.handler
    events:
      - httpApi: 'GET /fruits/{fruitName}'
      - httpApi: 'POST /fruits'

Any help is much appreciated.


Solution

  • The issue was identical variable naming causing a overwrite. And the following would fix that.

    app.get('/fruits/:fruitName', (req, res) => {
        const params = {
            TableName: TABLE_NAME,
            Key: {
                fruitName: req.params.fruitName,
            },
        }
        dynamoDB.get(params, (err, result) => {
            if (err) {
                console.log(error);
                res.status(400).json({ error: 'Could not get fruit' });
            }
            if (result.Item) {
                const { fruitName, biName} = result.Item;
                res.json({ fruitName, biName});
            } else {
                res.status(404).json({ error: "Fruit not found" });
            }
        })
    })