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?