Skip to content

Commit

Permalink
Merge pull request #348 from gvolpe/derivations/encoder-decoder
Browse files Browse the repository at this point in the history
Improve keyEncoder and keyDecoder impl
  • Loading branch information
gvolpe authored Apr 7, 2021
2 parents d43045d + d88940b commit 4fa3044
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
10 changes: 5 additions & 5 deletions modules/core/src/main/scala/shop/ext/circe/keyDecoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ object keyDecoder extends Derivation[KeyDecoder] with NewTypeDerivation[KeyDecod
type Typeclass[T] = KeyDecoder[T]

def combine[T](ctx: CaseClass[KeyDecoder, T]): KeyDecoder[T] = new KeyDecoder[T] {
def apply(key: String): Option[T] =
ctx.parameters.toList match {
case (p :: _) => p.typeclass.apply(key).map(_.asInstanceOf[T])
case _ => None
}
def apply(key: String): Option[T] = {
val parts = key.split("::")
if (parts.length != ctx.parameters.length) None
else ctx.constructMonadic(p => p.typeclass.apply(parts(p.index)))
}
}

def instance[T]: KeyDecoder[T] = macro Magnolia.gen[T]
Expand Down
21 changes: 12 additions & 9 deletions modules/core/src/main/scala/shop/ext/circe/keyEncoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ package shop.ext.circe

import derevo.{ Derivation, NewTypeDerivation }
import io.circe.KeyEncoder
import magnolia.{ CaseClass, Magnolia }
import magnolia.{CaseClass, Magnolia, SealedTrait}

object keyEncoder extends Derivation[KeyEncoder] with NewTypeDerivation[KeyEncoder] {
class keyEncoder(sep: String = "::") {
type Typeclass[T] = KeyEncoder[T]

def combine[T](ctx: CaseClass[KeyEncoder, T]): KeyEncoder[T] = new KeyEncoder[T] {
def apply(key: T): String =
ctx.parameters.toList match {
case (p :: _) => p.typeclass.apply(key.asInstanceOf[p.PType])
case _ => "error"
}
}
def combine[T](ctx: CaseClass[KeyEncoder, T]): KeyEncoder[T] =
if (ctx.isObject) _ => ctx.typeName.short
else { cc =>
ctx.parameters.view.map(p => p.typeclass(p.dereference(cc))).mkString(sep)
}

def dispatch[T](ctx: SealedTrait[KeyEncoder, T]): KeyEncoder[T] =
obj => ctx.dispatch(obj)(sub => sub.typeclass(sub.cast(obj)))

def instance[T]: KeyEncoder[T] = macro Magnolia.gen[T]
}

object keyEncoder extends keyEncoder("::") with Derivation[KeyEncoder] with NewTypeDerivation[KeyEncoder]

0 comments on commit 4fa3044

Please sign in to comment.