微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Serverless 调用本地数据类型问题

如何解决Serverless 调用本地数据类型问题

当我运行这个本地调用时,在我的 NodeJS lambda 中,有效负载object 而不是 string

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

这是有原因的吗?如何将此 json 负载作为字符串传递?

解决方法

问题的根源

根据AWS documentation:

运行时将三个参数传递给处理程序方法。第一个参数是事件对象,它包含来自调用者的信息。调用程序在调用 Invoke 时将此信息作为 JSON 格式的字符串传递,并且运行时将其转换为对象。当 AWS 服务调用您的函数时,事件结构因服务而异。

由于处理程序期望事件是一个“JSON 格式的字符串”,那么这个字符串将被转换为一个对象是正常的。

如何轻松解决此问题?

与其传递原始 JSON 并期望将其解析为字符串,不如将其包装到 JSON 字段之一中,例如:

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

对于这个输入和这个处理程序:

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)
};

我收到以下输出:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。