amnaredo / test

0 stars 0 forks source link

"read" not working correctly in scala JS #284

Open amnaredo opened 2 years ago

amnaredo commented 2 years ago

I have an experiment in which I'm attempting to use upickle to pass Json between client / server...

object Server extends cask.MainRoutes {

  @cask.get("/")
  def index() = {
    "Hello!"
  }

  @cask.postJson("/get-suggestions") 
  def suggest(search: String, prefixOnly: Option[Boolean]= None) = {
    println("ummmm")
    write(MyResponse(Seq("apple", "pear", "orange", "strawberries", "orangutan")))
  }
}
object Protocol {
  object GetSuggestions {

    case class MyRequest(search: String, prefixOnly: Option[Boolean] = None)
    object MyRequest {
      //implicit val codec = io.circe.generic.semiauto.deriveCodec[MyRequest]
      implicit val codec2: ReadWriter[MyRequest] = macroRW[MyRequest]
    }

    case class MyResponse(suggestions: Seq[String])
    object MyResponse {
      //implicit val codec = io.circe.generic.semiauto.deriveCodec[MyResponse]
      implicit val codec2: ReadWriter[MyResponse] = macroRW[MyResponse]
    }
  }
}
    val arg: Future[Response[Either[String,String]]] = req.send()
    dom.console.log("made request")
    dom.console.log(arg)
    val uhOh: Future[Either[String,MyResponse]] = arg.map(_.body.map{
      b => dom.console.log("-->" + b);
      val test = Try(read[MyResponse](b))
      println(test)
      read[MyResponse](b)}
    )
dom.console.log("Exception thrown before this message")
[Log] -->"{\"suggestions\":[\"apple\",\"pear\",\"orange\",\"strawberries\",\"orangutan\"]}" (dev.js, line 15780)
[Log] Failure(upickle.core.AbortException: expected dictionary got string at index 0) (dev.js, line 56688)

As far as I can tell, pickle is correctly "writing" the json. However, it fails to re-parse it coming back the other way, in scala JS.

val Scala      = "2.13.5"
  lazy val shared = Def.settings(    
    libraryDependencies += "com.softwaremill.sttp.client3" %%% "core" % "3.3.6",
    libraryDependencies += "com.lihaoyi" %%% "upickle" % "1.4.0"
  )
addSbtPlugin("org.scala-js"       % "sbt-scalajs"              % "1.6.0")

Would this be expected? ID: 352 Original Author: Quafadas

amnaredo commented 2 years ago

Okay, I take this back,

  @cask.postJson("/get-suggestions") 
  def suggest(search: String, prefixOnly: Option[Boolean]= None) = {
    println("ummmm")
    write(MyResponse(Seq("apple", "pear", "orange", "strawberries", "orangutan")))
  }

Changing this to

  @cask.post("/get-suggestions") 
  def suggest(request: cask.Request) = {

    val test = request.text()
    println(test)
    write(MyResponse(Seq("apple", "pear", "orange", "strawberries", "orangutan")))
  }

Actually fixes the problem. Which is weird as - it does not make any sense to me, how this could change the clientside behaviour... but hey ho Original Author: Quafadas