スプレーを使用して Scala で汎用 HTTP クライアントを作成しようとしています。クラス定義は次のとおりです。
object HttpClient extends HttpClient
class HttpClient {
implicit val system = ActorSystem("api-spray-client")
import system.dispatcher
val log = Logging(system, getClass)
def httpSaveGeneric[T1:Marshaller,T2:Unmarshaller](uri: String, model: T1, username: String, password: String): Future[T2] = {
val pipeline: HttpRequest => Future[T2] = logRequest(log) ~> sendReceive ~> logResponse(log) ~> unmarshal[T2]
pipeline(Post(uri, model))
}
val genericResult = httpSaveGeneric[Space,Either[Failure,Success]](
"http://", Space("123", IdName("456", "parent"), "my name", "short_name", Updated("", 0)), "user", "password")
}
オブジェクトutils.AllJsonFormats
には次の宣言があります。すべてのモデル形式が含まれています。同じクラスが「反対側」で使用されます。つまり、API も作成し、同じフォーマッターをスプレー缶とスプレー json で使用しました。
object AllJsonFormats
extends DefaultJsonProtocol with SprayJsonSupport with MetaMarshallers with MetaToResponseMarshallers with NullOptions {
もちろん、そのオブジェクトには、models.api.Space、models.api.Failure、models.api.Success のシリアル化の定義があります。
タイプは問題ないようです。Space
つまり、ジェネリックメソッドに を受け取って返すことを伝えると、Space
エラーは発生しません。しかし、メソッド呼び出しにいずれかを入れると、次のコンパイラ エラーが発生します。
タイプ Spray.httpx.unmarshalling.Unmarshaller[Either[models.api.Failure,models.api.Success]] の証拠パラメーターの暗黙的な値が見つかりませんでした。
私の期待は、spray.json.DefaultJsonProtocol 内、つまり、spray.json.StandardFormts 内のいずれかが暗黙的にカバーされることでした。
以下は、私の HttpClient クラスであり、一般的であることが最善です: 更新: より明確で反復可能なコード サンプル
object TestHttpFormats
extends DefaultJsonProtocol {
// space formats
implicit val idNameFormat = jsonFormat2(IdName)
implicit val updatedByFormat = jsonFormat2(Updated)
implicit val spaceFormat = jsonFormat17(Space)
// either formats
implicit val successFormat = jsonFormat1(Success)
implicit val failureFormat = jsonFormat2(Failure)
}
object TestHttpClient
extends SprayJsonSupport {
import TestHttpFormats._
import DefaultJsonProtocol.{eitherFormat => _, _ }
val genericResult = HttpClient.httpSaveGeneric[Space,Either[Failure,Success]](
"https://api.com/space", Space("123", IdName("456", "parent"), "my name", "short_name", Updated("", 0)), "user", "password")
}
上記では、アンマーシャラーが解決されていない場合でも問題が発生します。助けていただければ幸いです..
ありがとう。