Created
February 23, 2018 15:35
-
-
Save aerohit/5b07058d916c0eb8797cd372fc8a1e8b to your computer and use it in GitHub Desktop.
argonaut sum types
This file contains 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
import com.vimpelcom.ep.common.Msisdn | |
import org.scalatest.FunSpecLike | |
import org.scalatest.Matchers | |
import argonaut._ | |
import Argonaut._ | |
sealed trait ChallengeProof2FAOutcome | |
case class ChallengeProof2FAFailure(status: String, meta: String) extends ChallengeProof2FAOutcome | |
case class ChallengeProof2FASuccess(msisdn: Msisdn) extends ChallengeProof2FAOutcome | |
object ChallengeProof2FAOutcome { | |
implicit val ChallengeProof2FAFailureCodec: CodecJson[ChallengeProof2FAFailure] = | |
casecodec2(ChallengeProof2FAFailure.apply, ChallengeProof2FAFailure.unapply)("status", "meta") | |
implicit val ChallengeProof2FASuccessCodec = | |
casecodec1(ChallengeProof2FASuccess.apply, ChallengeProof2FASuccess.unapply)("msisdn") | |
val failureDecoder: DecodeJson[ChallengeProof2FAFailure] = ChallengeProof2FAFailureCodec.Decoder | |
val successDecoder: DecodeJson[ChallengeProof2FASuccess] = ChallengeProof2FASuccessCodec.Decoder | |
implicit val ChallengeProof2FAOutcomeCodec: CodecJson[ChallengeProof2FAOutcome] = | |
CodecJson[ChallengeProof2FAOutcome]( | |
{ | |
case out: ChallengeProof2FAFailure => ChallengeProof2FAFailureCodec(out) | |
case out: ChallengeProof2FASuccess => ChallengeProof2FASuccessCodec(out) | |
}, | |
c => | |
failureDecoder(c).map(x => x: ChallengeProof2FAOutcome) ||| | |
successDecoder(c).map(x => x: ChallengeProof2FAOutcome) | |
) | |
} | |
class FakeSpec extends FunSpecLike with Matchers { | |
describe("Json parsing") { | |
it("should work") { | |
import ChallengeProof2FAOutcome.ChallengeProof2FAOutcomeCodec | |
val a: ChallengeProof2FAOutcome = ChallengeProof2FAFailure("status info", "meta info") | |
val b: ChallengeProof2FAOutcome = ChallengeProof2FASuccess("msisdn info") | |
val aJsonString = """{"status":"status info","meta":"meta info"}""" | |
val bJsonString = """{"msisdn":"msisdn info"}""" | |
a.asJson.toString shouldEqual aJsonString | |
b.asJson.toString shouldEqual bJsonString | |
Parse.decodeOption[ChallengeProof2FAOutcome](aJsonString).get shouldEqual ChallengeProof2FAFailure( | |
"status info", | |
"meta info" | |
) | |
Parse.decodeOption[ChallengeProof2FAOutcome](bJsonString).get shouldEqual ChallengeProof2FASuccess("msisdn info") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment