Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve keyEncoder and keyDecoder impl #348

Merged
merged 1 commit into from
Apr 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]