julienrf / play-json-derived-codecs

MIT License
191 stars 34 forks source link

make type renaming shorter #62

Open Stefanqn opened 6 years ago

Stefanqn commented 6 years ago

It seems like a lot of code just to e.g. rename Left and Right in Either:

  def eitherFormat[L: Format, R: Format](typeMap: Map[String, String] = Map("Left" -> "Error", "Right" -> "Ok"))(
      implicit
      derivedReads: Lazy[DerivedReads[Either[L, R]]],
      derivedOWrites: Lazy[DerivedOWrites[Either[L, R]]]): OFormat[Either[L, R]] = {
    type A = Either[L, R]
    val adapter = NameAdapter.identity

    def eitherTypeTagReads(map: Map[String, String]): TypeTagReads =
      new TypeTagReads {
        def reads[A](typeName: String, reads: Reads[A]): Reads[A] =
          (__ \ map.getOrElse(typeName, typeName)).read(reads)
      }

    def eitherTypeTagOWrites(map: Map[String, String]): TypeTagOWrites =
      new TypeTagOWrites {
        def owrites[A](typeName: String, owrites: OWrites[A]): OWrites[A] =
          OWrites[A](a => Json.obj(map.getOrElse(typeName, typeName) -> owrites.writes(a)))
      }

    OFormat[A](
      derivedReads.value.reads(eitherTypeTagReads(typeMap), adapter),
      derivedOWrites.value.owrites(eitherTypeTagOWrites(typeMap), adapter))
  }