tapir icon indicating copy to clipboard operation
tapir copied to clipboard

[Question] how map ADTs to query parameter

Open a-bayat opened this issue 4 years ago • 3 comments

I have declared an ADT like bellow:

  sealed trait Gateway extends Serializable with Product
  object Gateway {
    case object XXX extends Gateway
    case object YYY extends Gateway
    case object ZZZ extends Gateway
  }

and my endpoint is defined like bellow:

val callbackEndpoint: Endpoint[
    (Gateway, BankTransactionId),
    (StatusCode, ErrorInfo),
    TransactionStatus,
    Any
  ] = {
    endpoint.get
      .in(basePath)
      .in(query[String]("gateway").mapTo[Gateway])
      .in(query[String]("transaction_id").mapTo[BankTransactionId])
      .out(jsonBody[TransactionStatus].example(SampleModels.transactionCallback))
      .errorOut(statusCode.and(jsonBody[ErrorInfo]))

  }

So Because gateway query mapTo is not case class It wouldn't compile. so to overcome I created a case class:

  final case class GatewayType(value: Gateway) extends AnyVal

and .in(query[Gateway]("gateway").mapTo[GatewayType]) but It need a complex implicit conversion. is there any solution to solve it.

a-bayat avatar Dec 18 '21 08:12 a-bayat

I'm surprised that wrapping this into a value class works ;)

I think if you are using an enum inside a query, you'll need a Codec for that type. See https://tapir.softwaremill.com/en/latest/endpoint/validation.html#enum-validators. I suspect adding

implicit def plainCodecFor Gateway: PlainCodec[Gateway] = {
  Codec.derivedEnumeration[String, Gateway](...)
}

should work - you'll need to provide the string <-> Gateway translation, though

adamw avatar Dec 23 '21 12:12 adamw

I've implemented tapir through tapir-redoc-akka-http and tapir-openapi-docs and tapir-openapi-circe-yaml and tapir-sttp-client version 0.18.3 and I dont't know why it doesn't include derivedEnumeration from Codec.derivedEnumeration[String, Gateway]. I have imported sttp.tapir._ and sttp.tapir.Codec.PlainCodec. I also tested core tapir it doesn't include, I couldn't figure out what the problem is

a-bayat avatar Dec 25 '21 06:12 a-bayat

@AmirhosseinBayat I think this might be absent in the 0.18 line, can you try 0.19.x?

adamw avatar Jan 03 '22 10:01 adamw