Last active
March 24, 2017 05:24
-
-
Save takkkun/d4c880da66309dcb361751fd80710b2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class JsonRpcBody[P <: Product](jsonrpc: String, method: String, params: P, id: String) | |
case class SampleParams(_1: String, _2: Int) extends Product2[String, Int] | |
// JsonRpcBody[SampleParams] にデコードするためには、DecodeJson[JsonRpcBody[SampleParams]] を | |
// 定義する必要がある。しかし、SampleParams 以外にも増えるのは予想され、その度に DecodeJson[JsonRpcBody[OtherParams]] などを | |
// 書くと大変めんどう。params の解釈の仕方が違うだけなのに、jsonrpc, method, id の部分も解釈しなきゃだし。 | |
// と言うわけで以下のように書く。 | |
implicit def jsonRpcBodyDecodeJson[P <: Product](implicit paramsDecodeJson: DecodeJson[P]): DecodeJson[JsonRpcBody[P]] = | |
DecodeJson(c => for { | |
jsonrpc <- (c --\ "jsonrpc").as[String] | |
method <- (c --\ "method").as[String] | |
params <- (c --\ "params").as[P] | |
id <- (c --\ "id").as[String] | |
} yield JsonRpcBody(jsonrpc, method, params, id)) | |
implicit def sampleParamsDecodeJson: DecodeJson[SampleParams] = | |
DecodeJson(c => for { | |
_1 <- c.downN(0).as[String] | |
_2 <- c.downN(1).as[Int] | |
} yield SampleParams(_1, _2)) | |
// これが欲しかったやつ | |
implicit def jsonRpcBodyWithSampleParams: DecodeJson[JsonRpcBody[SampleParams]] = jsonRpcBodyDecodeJson[SampleParams] | |
// implicit def jsonRpcBodyWithOtherParams: DecodeJson[JsonRpcBody[OtherParams]] = jsonRpcBodyDecodeJson[OtherParams] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment