The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details:

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { User, allUsers } from './users';
import { Commentary } from './domain';
import { dynamoDbClient } from './store';
import { PutCommand } from "@aws-sdk/client-dynamodb";

export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
    try {

        let status: number = 200;
        let commentary: Commentary = JSON.parse(event.body);
        console.log("deserialized this into commentary");
        console.log("and the deserialized commentary has content of: " + commentary.getContent());
        provideCommentary(event.body);
        responseBody = "\"message\": \"received commentary -- check dynamoDb!\"";

        return {
            statusCode: status,
            body: responseBody
        };

    } catch (err) {
        console.log(err);
        return {
            statusCode: 500,
            body: JSON.stringify({
                message: err.stack,
            }),
        };
    }
};

const provideCommentary = async (commentary: Commentary) => {
  // Set the parameters.
  const params = {
    TableName: "commentary-dev",
    Item: {
      id: commentary.getId(),
      content: commentary.getContent(),
      createdAt : commentary.getCreatedAt(),
      providerId: commentary.getProviderId(),
      receiverId: commentary.getReceiverId()
    },
  };
  try {
    const data = await ddbDocClient.send(new PutCommand(params));
    console.log("Success - item added or updated", data);
  } catch (err) {
    console.log("Error", err.stack);
    throw err;
  }
};

Now, the structure for the Commentary class in domain.ts is as follows:

class Commentary {
  private id: number;
  private content: string;
  private createdAt: Date;
  private providerId: number;
  private receiverId: number;

  constructor(id: number, content: string, createdAt: Date, providerId: number, receiverId: number) {
    this.id = id;
    this.content = content;
    this.createdAt = createdAt;
    this.providerId = providerId;
    this.receiverId = receiverId;
  }

  public getId(): number {
    return this.id;
  }

  public getContent(): string {
    return this.content;
  }

  public getProviderId(): number {
    return this.providerId;
  }

  public getReceiverId(): number {
    return this.receiverId;
  }

}

export { Commentary };

When invoking the Lambda via command-line curl, using the specified parameters:

curl --request POST 'https://<mylambda>/commentary' \
--header 'Content-Type: application/json' -d '{"id":123,"content":"test commentary","createdAt":"2022-12-02T08:45:26.261-05:00","providerId":456,"receiverId":789}'

The error encountered reads:

{"message":"TypeError: r.getContent is not a function\n

Can you spot why the deserialization of event.body into a Commentary is causing issues?

Answer №1

You need to properly instantiate a Commentary object here. Simply assigning the parsed body to the commentary variable won't create an instance.

const { id, content, createdAt, providerId, receiverId } = JSON.parse(event.body);

const commentaryInstance = new Commentary(id, content, createdAt, providerId, receiverId);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Service for Posting in Angular

I am looking to enhance my HTTP POST request by using a service that can access data from my PHP API. One challenge I am facing is figuring out how to incorporate user input data into the services' functionality. Take a look at the following code snip ...

Displaying customized local JSON information in a Tabulator Table

I'm trying to incorporate local JSON data into a table using Tabulator. Specifically, I want to display the element obj.File.Name from the JSON. While I can render the data in a regular table, I face issues when trying with Tabulator as the data does ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Automate brush control and transmit pertinent data through coding

Extending on the query from yesterday's thread, I am working towards implementing multiple brushes. While my current brute force method is functional, I require additional functionality to programmatically manage each of these newly created brushes. ...

Issue with React and Mongoose: State Change Not Being Saved

I am facing an issue with changing the state of my checkbox. Initially, the default option in my Mongoose model is set to false. When a user checks the box and submits for the first time, it successfully updates their profile (changing the value to true). ...

What is the best way to dynamically generate and update the content of a select input in an Angular form using reactive programming techniques?

I have successfully developed an Angular reactive form that includes a select field populated dynamically with values retrieved from an API call. In addition, I have managed to patch the form fields with the necessary data. My current challenge is to dyn ...

Using the Unsigned Right Shift Operator in PHP (Similar to Java/JavaScript's >>> Operator)

Before marking this as a duplicate, please take a moment to read the information below and review my code * my updated code! The issue I am facing is that I need to implement Java/JavaScript '>>>' (Unsigned Right Shift / Zero-fill Right Shift) ...

``JsViews and AngularJS: A Comparison"

I'm exploring the possibility of creating a single page application and came across jsViews/jsRender which seems very promising as it approaches Beta. As someone new to SPA development, I'm interested in understanding how jsViews stacks up agains ...

In what scenario would one require an 'is' predicate instead of utilizing the 'in' operator?

The TypeScript documentation highlights the use of TypeGuards for distinguishing between different types. Examples in the documentation showcase the is predicate and the in operator for this purpose. is predicate: function isFish(pet: Fish | Bird): pet ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

What methods does MaterialUI utilize to achieve this?

Have you checked out the autocomplete feature in their component? You can find it here: https://mui.com/material-ui/react-autocomplete/ I noticed that after clicking on a suggestion in the dropdown, the input box retains its focus. How do they achieve thi ...

Customizing the `toString()` method in Node.js exports

I'm having trouble overriding a toString() method in my code. I've already checked here and here, but haven't been able to solve the issue. This is what my code looks like: var Foo = function(arg) { // some code here... return fun ...

Executing an http.get request in Angular2 without using RxJS

Is there a method to retrieve data in Angular 2 without using Observable and Response dependencies within the service? I believe it's unnecessary for just one straightforward request. ...

Trouble integrating PDF from REST API with Angular 2 application

What specific modifications are necessary in order for an Angular 2 / 4 application to successfully load a PDF file from a RESTful http call into the web browser? It's important to note that the app being referred to extends http to include a JWT in ...

Inferring types from synchronous versus asynchronous parameters

My objective is to create an "execute" method that can deliver either a synchronous or an asynchronous result based on certain conditions: type Callback = (...args: Arguments) => Result const result: Result = execute(callback: Callback, args: Arguments) ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

Create a hover effect on HTML map area using CSS

Is it possible to change the background color of an image map area on hover and click without using any third-party plugins? I attempted the following code: $(document).on('click', '.states', function(){ $(this).css("backgro ...

What is the best method to initialize a JavaScript function only once on a website that uses AJAX

Currently, I am facing an issue with a javascript function that needs to be contained within the content element rather than in the header. This is due to a dynamic ajax reload process which only refreshes the main content area and not the header section. ...

Processing made easy with jQuery

In my HTML page, I have multiple rows that represent records from a database. Each row contains input fields and a link at the end. When I click on the link, I need to capture the values of the input fields within the same row. Here is an example of the H ...