Search code examples
scalasttptapirmagnolia-scala

Implicitly getting Schema from class with type Alias


I'm currently using sttp version 3.3.14 with tapir version 0.18.0-M15 and I'm having trouble with the Schemas of certain case classes. More specifically, case classes that contain type aliases.

Here is a simple custom Codec for Either:

import cats.implicits._
import io.circe.syntax._
import io.circe.{Codec, Decoder, Encoder}
import sttp.tapir.Schema
import io.circe.generic.semiauto._
import sttp.tapir.generic.auto._

object codecs {
  private def eitherDecoder[A, B](implicit a: Decoder[A], b: Decoder[B]): Decoder[Either[A, B]] = a.map(_.asLeft[B]) or b.map(_.asRight[A])
  private def eitherEncoder[A, B](implicit a: Encoder[A], b: Encoder[B]): Encoder[Either[A, B]] =
    Encoder.instance(_.fold(_.asJson, _.asJson))
  implicit def eitherCodec[A, B](implicit aE: Encoder[A], bE: Encoder[B], a: Decoder[A], b: Decoder[B]): Codec[Either[A, B]] =
    Codec.from(eitherDecoder, eitherEncoder)
}

The following code works just fine:

object SuccessCase extends App {

  import codecs.eitherCodec

  case class Cls(i: Either[String, Int])

  implicit val codec: Codec[Cls] = deriveCodec[Cls]

  val schema = implicitly[Schema[Cls]]
}

But this test case fails. Note that the only difference is the Either alias.

object FailureCase extends App {

  import codecs.eitherCodec

  type EitherAlias = Either[String, Int]
  case class Cls(i: EitherAlias)

  implicit val codec: Codec[Cls] = deriveCodec[Cls]

  val schema = implicitly[Schema[Cls]]

  //Fails with error:
  //  Could not find Schema for type com.xxx.FailureCase.Cls.
  //  Since 0.17.0 automatic derivation requires the following import: `import sttp.tapir.generic.auto._`
  //  You can find more details in the docs: https://tapir.softwaremill.com/en/latest/endpoint/customtypes.html#schema-derivation
  //  When using datatypes integration remember to import respective schemas/codecs as described in https://tapir.softwaremill.com/en/latest/endpoint/integrations.html
  //  val schema = implicitly[Schema[Cls]]

  //  (sttp.tapir.generic.auto._ is imported)
}

Any idea on what may be wrong here or how to solve this?

Thanks!


Solution

  • Was using tapir version 0.18.0-M15. Problem seems to have been solved in version 0.19