arielweinberger / sls-base

Base template for Serverless Framework applications
154 stars 132 forks source link

going through tutorial after adding middy to createAuction I get 502 #9

Open joshbedo opened 3 years ago

joshbedo commented 3 years ago

Not too sure whats going on I followed the tutorial and for some reason createAuction returns internal server error. When i look at the logs in Cloudwatch it says SyntaxError: Unexpected token o in JSON at position 1. Seems like it's trying to parse JSON thats already a JS object or something. Am I missing something?

Screen Shot 2021-08-02 at 3 14 36 AM

Screen Shot 2021-08-02 at 3 15 42 AM

Screen Shot 2021-08-02 at 3 16 54 AM

joshbedo commented 3 years ago

Figured out part of it still had JSON.parse(event.body) in createAuction removed that and now its creating records.. for some reason I'm still getting Internal Server Error but no errors show in the Cloudwatch logs now.

EDIT: I think it's just a stale response because error returns something but success returns nothing. I just returned a 201 status code and everything looks good now. Switched it to the code below so it returns the auction created with 201.. if the record fails to create it will throw the Internal Server Error message.

import { v4 as uuid } from 'uuid';
import AWS from 'aws-sdk';
import commonMiddleware from '../lib/commonMiddleware';
import createError from 'http-errors';

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

async function createAuction(event, context) {
  let created;

  const { title } = event.body;
  const now = new Date();

  const auction = {
    id: uuid(),
    title,
    status: 'OPEN',
    createdAt: now.toISOString(),
    highestBid: {
      amount: 0,
    }
  };

  try {
    await dynamodb.put({
      TableName: process.env.AUCTIONS_TABLE_NAME,
      Item: auction,
    }).promise();  

    return {
      statusCode: 201,
      body: JSON.stringify(auction),
    };
  } catch(err) {
    console.error(err);
    throw new createError.InternalServerError();
  }
}

export const handler = commonMiddleware(createAuction);