gpt4 book ai didi

scala - Finch:方法 'toService' 的参数不足

转载 作者:行者123 更新时间:2023-12-02 03:54:35 25 4
gpt4 key购买 nike

我使用 Finch 和 Finagle 制作了一个非常简单的休息方法:

val getUsers:Endpoint[List[User]] = get("users") {Ok(getAllUsers())}
Http.serve(":8080", getUsers.toService)

并收到此错误:

Error:(50, 32) not enough arguments for method toService: (implicit ts: io.finch.internal.ToService[List[DAL.Instances.User.User]])com.twitter.finagle.Service[com.twitter.finagle.http.Request,com.twitter.finagle.http.Response].
Unspecified value parameter ts.
Http.serve(":8080", getUsers.toService)
^

知道如何解决这个问题吗?

最佳答案

最新版本的 Finch (0.10) 中的编译器错误情况有所改善。如果我们有以下构建配置:

scalaVersion := "2.11.7"

libraryDependencies += "com.github.finagle" %% "finch-core" % "0.10.0"

这个设置:

import com.twitter.finagle.Http
import io.finch._

case class User(id: String, name: String)

def getAllUsers(): List[User] = List(User("111", "Foo McBar"))
val getUsers: Endpoint[List[User]] = get("users") { Ok(getAllUsers()) }

然后,当我们尝试使用 toService 时,我们得到以下结果:

<console>:18: error: You can only convert a router into a Finagle service if the
result type of the router is one of the following:

* A Response
* A value of a type with an EncodeResponse instance
* A coproduct made up of some combination of the above

List[User] does not satisfy the requirement. You may need to provide an
EncodeResponse instance for List[User] (or for some part of List[User]).

Http.serve(":8080", getUsers.toService)
^

问题是您没有告诉 Finch 如何将您的 User 类型的实例转换为 HTTP 响应。 Finch 的 EncodeResponsetype class 的一个示例,这是一种多态性方法,广泛用于 Scala(包括标准库)和许多其他静态类型函数编程语言。

提供适当 EncodeResponse 实例的最简单方法是添加 Finch 的 Circe您的构建的兼容性模块:

libraryDependencies ++= Seq(
"io.circe" %% "circe-generic" % "0.3.0",
"com.github.finagle" %% "finch-circe" % "0.10.0"
)

然后您所需要的只是以下导入:

import io.finch.circe._, io.circe.generic.auto._

并且 toService 会正常工作:

scala> Http.serve(":8080", getUsers.toService)
Feb 26, 2016 8:32:24 AM com.twitter.finagle.Init$$anonfun$1 apply$mcV$sp
INFO: Finagle version 6.33.0 (rev=21d0ee8b5070b735eda5c84d7aa6fbf1ba7b1635) built at 20160203-202859
res2: com.twitter.finagle.ListeningServer = Group(/0:0:0:0:0:0:0:0:8080)

现在,如果您访问 http://localhost:8080/users,您将看到以下内容:

[{"id":"111","name":"Foo McBar"}]

这看起来很神奇,但所发生的事情是相当有原则的。 Circe是一个 JSON 库,提供通用编解码器派生,可在编译时确定如何将案例类表示为 JSON 值(有关更多上下文,请参阅我的博客文章 here)。

Finch cookbook是了解有关此类问题的更多信息的绝佳资源,第一部分详细介绍了提供 toService 所需的 EncoderResponse 实例的其他方法。如果您还有任何其他问题或上述任何疑问,请随时在此处或通过 Gitter 提问。 .

关于scala - Finch:方法 'toService' 的参数不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35646410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com