【问题标题】:AWS Lambda - Java BeansAWS Lambda - Java Bean
【发布时间】:2018-03-06 21:05:46
【问题描述】:

我的请求如下所示:

package pricing

import scala.beans.BeanProperty

class Request(@BeanProperty var name: String, @BeanProperty var surname: String) {
  def this() = this(name="defName", surname="defSurname")
}

处理程序如下:

package pricing

import com.amazonaws.services.lambda.runtime.{Context, RequestHandler}
import scala.collection.JavaConverters
import spray.json._


class ApiGatewayHandler extends RequestHandler[Request, ApiGatewayResponse] {

  import DefaultJsonProtocol._

  def handleRequest(input: Request, context: Context): ApiGatewayResponse = {
    val headers = Map("x-foo" -> "coucou")
    val msg = "Hello " + input.name
    val message = Map[String, String]("message" -> msg )
    ApiGatewayResponse(
      200,
      message.toJson.toString(),
      JavaConverters.mapAsJavaMap[String, Object](headers),
      true
    )
  }
}

已被记录为:

functions:
  pricing:
    handler: pricing.ApiGatewayHandler
    events:
      - http:
          path: pricing/test
          method: get
          documentation:
            summary: "submit your name and surname, the API says hi"
            description: ".. well, the summary is pretty exhaustive"
            requestBody:
              description: "Send over name and surname"
            queryParams:
              - name: "name"
                description: "your 1st name"
              - name: "surname"
                description: ".. guess .. "
            methodResponses:
              - statusCode: "200"
                responseHeaders:
                  - name: "x-foo"
                    description: "you can foo in here"
                responseBody:
                  description: "You'll see a funny message here"
                responseModels:
                  "application/json": "HelloWorldResponse"

好吧,这是其中一个教程的复制和粘贴。它不工作。 我猜BeanProperty 指的是body 对象属性;这就是我可以从示例here 中猜到的。

如果我想要查询字符串?

尝试过:

package pricing

import scala.beans.BeanProperty
import spray.json._

abstract class ApiGatewayGetRequest(
                                     @BeanProperty httpMethod: String,
                                     @BeanProperty headers: Map[String, String],
                                     @BeanProperty queryStringParameters: Map[String, String])


abstract class ApiGatewayPostRequest(
                                     @BeanProperty httpMethod: String,
                                     @BeanProperty headers: Map[String, String],
                                     @BeanProperty queryStringParameters: Map[String, String])

class HelloWorldRequest(
                         @BeanProperty httpMethod: String,
                         @BeanProperty headers: Map[String, String],
                         @BeanProperty queryStringParameters: Map[String, String]
                       ) extends ApiGatewayGetRequest(httpMethod, headers, queryStringParameters) {

  private def getParam(param: String): String =
    queryStringParameters get param match {
      case Some(s) => s
      case None => "default_" + param
    }

  def name: String = getParam("name")
  def surname: String = getParam("surname")

  def this() = this("GET", Map.empty, Map.empty)

}

结果:

 {
  "message":"Hello default_name"
 }

建议该类已使用空映射代替 queryStringParameters 进行初始化,但已正确提交

 Mon Sep 25 20:45:22 UTC 2017 : Endpoint request body after
 transformations:
 {"resource":"/pricing/test","path":"/pricing/test","httpMethod":"GET","headers":null,"queryStringParameters":{"name":"ciao", "surname":"bonjour"},"pathParameters":null,"stageVariables":null,
 ...

注意: 我之所以走这条路,是因为我觉得将@BeanProperty queryStringParameters: Map[String, String] 中的Map 替换为T 类型会方便且富有表现力,例如

case class Person(@beanProperty val name: String, @beanProperty val surname: String)

但是,上面的代码将{"name":"ciao", "surname":"bonjour"} 视为String,但没有弄清楚它应该反序列化该字符串。

编辑

我也尝试用java.util.Map[String, String] 替换 scala 映射但没有成功

【问题讨论】:

  • 你能以任何方式获得像{"name":"ciao", "surname":"bonjour"} 这样的字符串吗?在这么多(如果可能的话)你可以创建一个对象来保存(从字符串解析)数据?将字符串条目解析为 Java 对象对您来说是一种可能的解决方案吗?

标签: java scala aws-lambda aws-api-gateway serverless-framework


【解决方案1】:

默认情况下,无服务器启用proxy integration between the lambda and API Gateway。正如您所注意到的,这对您来说意味着 API 网关会将包含有关请求的所有元数据的对象传递给您的处理程序:

2017 年 9 月 25 日星期一 20:45:22 UTC:转换后的端点请求正文:{"resource":"/pricing/test","path":"/pricing/test","httpMethod":"GET" ,"headers":null,"queryStringParameters":{"name":"ciao", "surname":"bonjour"},"pathParameters":null,"stageVariables":null, ...

这显然不会映射到您的模型,其中只有字段 namesurname。有几种方法可以解决这个问题。

1。调整您的模型

如果您通过使字段可变(并因此为它们创建设置器)使您的类成为适当的 POJO,那么您对 ​​HelloWorldRequest 类的尝试确实有效:

class HelloWorldRequest(
                         @BeanProperty var httpMethod: String,
                         @BeanProperty var headers: java.util.Map[String, String],
                         @BeanProperty var queryStringParameters: java.util.Map[String, String]
                       ) extends ApiGatewayGetRequest(httpMethod, headers, queryStringParameters) {

AWS Lambda 文档states

需要 get 和 set 方法才能使 POJO 与 AWS Lambda 的内置 JSON 序列化程序一起使用。

另外请记住,Scala 的 Map 不受支持。

2。使用自定义请求模板

如果您不需要元数据,那么您可以使用mapping templates 让 API Gateway 仅将您需要的数据传递给 lambda,而不是更改模型。

为此,您需要告诉 Serverless 使用普通 lambda 集成(而不是代理)和 specify a custom request template

Amazon API Gateway 文档有 an example request template,这几乎可以完美解决您的问题。稍微剪裁一下,我们就得到了

functions:
  pricing:
    handler: pricing.ApiGatewayHandler
    events:
      - http:
          path: pricing/test
          method: get
          integration: lambda
          request:
            template:
              application/json: |
                #set($params = $input.params().querystring)
                {
                #foreach($paramName in $params.keySet())
                  "$paramName" : "$util.escapeJavaScript($params.get($paramName))"
                  #if($foreach.hasNext),#end
                #end
                }

此模板将从查询字符串参数中生成一个 JSON,它现在将成为 lambda 的输入:

转换后的端点请求正文:{ "name" : "ciao" }

正确映射到您的模型。

请注意,禁用代理集成也会更改响应格式。您会注意到现在您的 API 直接返回您的响应模型:

{"statusCode":200,"body":"{\"message\":\"Hello ciao\"}","headers":{"x-foo":"coucou"},"base64Encoded" :true}

您可以通过修改代码以仅返回正文或添加自定义响应模板来解决此问题:

          response:
            template: $input.path('$.body')

这会将输出转换为您所期望的,但会公然忽略statusCodeheaders。您需要进行更复杂的响应配置来处理这些问题。

3。自己做映射

不要扩展 RequestHandler 并让 AWS Lambda 将 JSON 映射到 POJO you can instead extend RequestStreamHandler,这将为您提供 InputStreamOutputStream,因此您可以使用 JSON 进行(反)序列化您选择的序列化程序。

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 2020-06-04
    • 2018-08-02
    • 1970-01-01
    • 2016-10-27
    • 2016-03-14
    • 2015-10-29
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多