Warm tip: This article is reproduced from serverfault.com, please click

API return writeable

发布于 2020-12-11 14:14:20

I'm trying to convert a few endpoints I have to use concurrency. I have the following method for the controller:

Original method

def getHistory(id:String) = Action {
  val response = historyService.getPersonHistory(id)

  Ok(write(response)) as "application/json"
}

New Method

def getHistory(id:String) = Action.async {
    val response = scala.concurrent.Future {
        historyService.getPersonHistory(id)
    }

   response.map(i => Ok(i))

}

So, when we try this with a simple example process (not calling another method, but just calculating an Int) it seems to work. In the new version above, I keep getting the error:

"No implicits found for parameter writable: Writeable[historyResponse]

Cannot write an instance of models.HistoryResponse to HTTP response. Try to define a Writeable[models.HistoryResponse]"

I'm new to Scala, and having difficulty finding information on making writeables. What do I need to be able to return the results as before?

Thanks

Questioner
Limey
Viewed
0
AminMal 2020-12-11 23:34:21

You need to define an implicit val tjs: Writes[HistoryResponse] or even better, implicit val format: Format[HistoryResponse] = Json.format[HistoryResponse] in the companion object for HistoryResponse, so that play can auto convert your data to json. by the way, not a good name for i in the map function, something like "history" would be better instead of "i".