【问题标题】:Spray: query as part of URI or parameterSpray:查询作为 URI 或参数的一部分
【发布时间】:2015-12-22 14:13:25
【问题描述】:

我尝试允许 API 有两种使用方式:要么提供查询作为 URI 的一部分,要么提供它作为参数。

端点

/search/myQuery 等同于/search?query=myQuery

两者都应该返回相同的结果。

代码

这是我目前正在使用的实现。不过感觉有点笨拙,因为很多代码需要重复。

path("search") {
  parameter('query) { term =>
    get {
     complete { performSearch(term) }
    }
} ~
path("search" / Segment) { searchTerm =>
  get {
    complete { performSearch(term) }
  }
}

问题

在 Spray 中是否有更 DRY 的方式来表达这种行为?

【问题讨论】:

    标签: scala rest spray


    【解决方案1】:

    Spray 具有非常强大的组合器,因此它是非常简单的任务。

    val pathOrParameter = path(Segment) | parameter('search)
    
    path("search") {
      pathOrParameter { term =>
        get {
         complete { performSearch(term) }
        }
      }
    }
    

    除此之外,您还可以进一步组合:

    val searchApi = get & path("search") & (path(Segment) | parameter('search))
    
    searchApi { term =>
      complete { performSearch(term) }
    }
    

    Custom Directive 页面详细解释了 spray 编写指令的能力。

    【讨论】:

    • 非常感谢 :) 我已经按照您之前的描述进行了尝试,但没有括号 (path(Segment) | parameter('search))它无法编译。 `
    • 它是类型安全的,所以如果类型不同,它将无法编译。例如get 的类型为Directive0parameter('search) 的类型为Directive1[String],所以get | parameter('search) 不会编译。
    • 链接到“自定义指令”页面返回 404 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多