Skip to content

Instantly share code, notes, and snippets.

@kareblak
Last active January 30, 2024 12:54
Show Gist options
  • Save kareblak/ae5165239755a43275fa4c807f0d647f to your computer and use it in GitHub Desktop.
Save kareblak/ae5165239755a43275fa4c807f0d647f to your computer and use it in GitHub Desktop.
Transformations between `monix.NewtypeWrapped` and `smithy4s.Newtype` with ducktape
import smithy4s.ShapeId
import smithy4s.Bijection
import smithy4s.Hints
import smithy4s.Newtype
import smithy4s.Schema
import smithy4s.schema.Schema.bijection
import smithy4s.schema.Schema.string
import io.github.arainko.ducktape.*
import monix.newtypes.*
import scala.Either
type Maybe[+T] = Either[String, T]
given toMonixNewtypeTransformer[T, M, S](using
builder: HasBuilder.Aux[M, T],
bijection: Bijection[builder.Source, S]
): Transformer.Fallible[Maybe, S, M] =
(s: S) =>
builder.build(bijection.from(s)).left.map(_.toReadableString)
given fromMonixNewtypeTransformer[T, M, S](using
extractor: HasExtractor.Aux[M, T],
bijection: Bijection[extractor.Source, S]
): Transformer[M, S] =
(m: M) =>
bijection.to(extractor.extract(m))
type Bar = Bar.Type
object Bar extends NewtypeWrapped[String]
type Foo = Foo.Type
object Foo extends Newtype[String] {
val id: ShapeId = ShapeId("newtypes", "UserId")
val hints: Hints = Hints.empty
val underlyingSchema: Schema[String] = string.withId(id).addHints(hints)
implicit val schema: Schema[Foo] = bijection(underlyingSchema, asBijection)
}
given Transformer.Mode.FailFast[Maybe] =
Transformer.Mode.FailFast.either[String]
val foo: Foo = Foo("foo")
val bar = foo.fallibleTo[Bar]
println(bar)
val foo2 = bar.to[Foo]
println(foo2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment