0
votes

When I run this local invoke, in my NodeJS lambda the payload comes as an object instead of string

serverless invoke local -f MyfunctionName --data '{ "data": "hello world" }'

Is there a reason for this? How can I pass this json payload as a string?

1

1 Answers

0
votes

Source of the problem

According to AWS documentation:

The runtime passes three arguments to the handler method. The first argument is the event object, which contains information from the invoker. The invoker passes this information as a JSON-formatted string when it calls Invoke, and the runtime converts it to an object. When an AWS service invokes your function, the event structure varies by service.

Since handler expects event to be a "JSON-formatted string", then it's normal, that this string will be converted into an object.

How to easily workaround it?

Instead of passing raw JSON and expecting it to be parsed as string, simply wrap it into one of JSON fields, an example:

serverless invoke local -f MyfunctionName --data '{"inputJson": "{ \"data\": \"hello world\" }"}'

For this input and this handler:

export const handler = async (event, context) => {
  console.log('type of event.inputJson = ' + typeof event.inputJson)
  console.log('value of event.inputJson = ' + event.inputJson)
  const parsedInputJson = JSON.parse(event.inputJson)
  console.log('value of inputJson.data = ' + parsedInputJson.data)
};

I'm receiving following output:

type of event.inputJson = string
value of event.inputJson = { "data": "hello world" }
value of inputJson.data = hello world