如何使用 Akka HTTP 呈现部分响应

How to render partial responses with Akka HTTP

我想使用 Akka HTTP 呈现部分响应。在请求中,客户端应指定要包含在响应中的字段(例如,使用 fields 请求参数,例如:https://www.acme.com/api/users/100?fields=id,name,address)。

如果有任何关于如何解决此问题的建议,我将不胜感激。

Akka http 提供了一个有用的 DSL,称为 Directives 来解决这些类型的问题。您可以匹配特定路径,然后提取 "fields" 键的 HttpRequest 查询字符串:

import akka.http.scaladsl.server.Directives._

val route = get {
  path("api" / "users" / IntNumber) { pathInt =>
    parameter('fields) { fields =>
      complete(generateResponse(pathInt, fields))
    }
  }
}

对于给定的示例请求 ("https://www.acme.com/api/users/100?fields=id,name,address"),将使用 100id,name,address 作为输入变量调用 generateResponse 函数。假设您要查找 table 个值:

case class Person(id : String, name : String, address : String, age : Int)

val lookupTable : Map[Int, Person] = ???

然后您可以使用此查找 table 获取此人并提取适当的字段:

def personField(person : Person)(field : String) = field match {
  case "id" => s"\"id\" = \"${person.id}\""
  case "name" => s"\"name\" = \"${person.name}\""
  ...
}

//generates JSON responses
def generateResponse(key : Int, fields : String) : String = {

  val person = lookupTable(key)

  "{ " + 
  fields
    .split(",")
    .map(personField(person))
    .reduce(_ + " " + _)
  + " }"
}