I am currently experimenting with testing a lambda function locally using the serverless framework. This particular function is connected to a POST endpoint, which is defined as:
createCat:
handler: app/handler.createCat
events:
- http:
path: cats/
method: post
To invoke this function locally, I followed the steps outlined in this source:
# Command line
serverless invoke local --function createCat --path local-invoke/createCat.json --stage local
# createCat.json
{
"body": {
"name": "Cat cat blue",
"age": 4,
"color": "blue"
}
}
In an attempt to parse the body and retrieve its contents as shown here, I implemented the following code snippet:
import { Context } from 'aws-lambda';
const createCat = async (event: any, context?: Context) => {
try{
const data = JSON.parse(event.body)
let name = data?.name
let age = Number(data?.age)
let color = data?.color
return {
statusCode: 500,
message: data
}
}
catch(error) {
return {
statusCode: 500,
body: JSON.stringify({
message: getMessageFromError(error)
})
}
}
}
However, instead of obtaining the parsed body, I am receiving the following output:
{
"statusCode": 500,
"body": "{\"message\":\"Unexpected token l in JSON at position 0\"}"
}
The Serverless documentation on local invoke does not provide guidance on how to pass or retrieve body parameters either.
Where could I be going wrong in this process?