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

Extract the names and corresponding keys from an array, then display them as a list

I am currently working on extracting key names and sub key names from a file in order to display the results in a list format as shown below. Anna was removed by AdminWhoRemoved due to Removal Reason Ethan was removed by AdminWhoRemoved due to Removal Re ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

How can Vue handle passing an array in this scenario?

In my code snippet, I am attempting to build a simple form builder application. The goal is to include multiple select fields in the form. I encountered a problem with passing an array into a loop. Despite my efforts, the code did not work as expected. Ho ...

Navigating after submitting a form using the Location header in jQuery

Seeking a way to utilize the Location header in jQuery 1.7 for redirection to a target. The current code is structured as follows: $('#creationLink').click(function(){ $.ajax({ type: 'POST', url: '/', success: ...

I'm experiencing issues with my AJAX as it fails to post or respond after the user clicks on the submit

I am currently working on implementing a list of events, each with a tick box and an x box for marking the event as complete or deleted. The challenge I'm facing is that when I click the buttons, nothing happens without refreshing the page. I suspect ...

URL from different domains

Currently, I am attempting to utilize this URL within my javascript code: Below is the snippet of my javascript code: $.ajax({ url: 'http://api.addressify.com.au/address/autoComplete', type: 'GET', crossDomain ...

The cookies() function in NextJS triggers a page refresh, while trpc consistently fetches the entire route

Is it expected for a cookies().set() function call to trigger a full page refresh in the new Next 14 version? I have a chart component that fetches new data at every interval change, which was working fine when fetching the data server-side. However, since ...

Using JQuery's change function with a Button Group is a great way

I encountered an issue where my button group works with the on.click function but not with on.change. <div class="ui buttons"> <button class="ui button">Value 1</button> <button class="ui bu ...

Discovering the center of an element and implementing a left float

I'm looking for a way to dynamically position the element #ucp_arrow in the middle of a div using float: left. Here is an illustration: https://i.stack.imgur.com/nzvgb.png Currently, I have hard-coded it like this: JAVASCRIPT: $("#a_account").cli ...

Determine ng-checked according to an array

I am working with a select dropdown that creates checkboxes using ng-repeat based on the selected value. The goal is to have all values in the dropdown selected, corresponding checkboxes checked, and store them in an array. Each time a checkbox is changed ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...

Complete and automatically submit a form in a view using AngularJS

I have developed a basic AngularJS application that is functioning smoothly. Currently, I am looking to populate certain fields and submit the form directly from the view without requiring any user input. Below, you'll find some simplified JavaScrip ...

Despite the presence of AWS CodeArtifact login configuration, npm login is still necessary

Despite successfully configuring npm to use the AWS CodeArtifact repository by AWS CodeArtifact (Successfully configured npm to use AWS CodeArtifact repository https://xxxxxx.d.codeartifact.xxxx.amazonaws.com/npm/xxxx-npm/), and having the correct configu ...

Enhancing Code Completion Feature for Multiline Strings in Visual Studio Code

When attempting to include HTML code in a multiline string using backticks within TypeScript, I've noticed that VS Code doesn't offer auto-completion for the HTML tags. Take this example: @Component({ selector: 'app-property-binding&ap ...

Issue encountered with Typescript and Mongoose while operating within a Kubernetes cluster environment with Skaffold configuration

Here is the code snippet, const userSchema = new mongoose.Schema({ email: { type: String, required: true, }, password: { type: String, required: true, }, }); console.log(userSchema); userSchema.statics.build = (user: UserAttrs) =& ...

Utilize the text box feature for manipulating the data field in Angular4

Within my grid view, there exists a column labeled remark. This specific field contains various values, one of which is absence. My objective is to modify the remark value exclusively when it is equal to absence, followed by clicking the corresponding icon ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

The value of the progress bar in Bootstrap Vue cannot be retrieved using a function

I have implemented a progress bar using Bootstrap Vue. Here is the HTML code: <b-progress :value="getOverallScore" :max=5 variant="primary" animated></b-progress> The getOverallScore function calculates an average value based on three differe ...

Implementing TypeScript with styled components using the 'as' prop

I am in the process of developing a design system, and I have created a Button component using React and styled-components. To ensure consistency, I want all my Link components to match the style and receive the same props as the Button. I am leveraging t ...