Is it possible to set Response Code from Marshaller in spray.io?

78 views Asked by At

I have following code snippet where dataService returns Option[LocationDataResult]. I would like to set NotFound when dataService returns None and send the data back in case of Some( ...).

I have following code:

  val route: Route = {
    pathPrefix("service" / "data") {
      pathPrefix( "infobox") {
        get {
          parameters(('mes.as[String], 'oks.as[String])) {
            (me, okr) =>

              val resp = dataService.ask(GetocationInfoboxData(me,okr)).mapTo[LocationInfoboxDataResult]
                .map(remapInfoboxToResponseObject(_)).map { r =>
                r match {
                  case None => StatusCodes.NotFound
                  case Some(dataToRespond) => dataToRespond
                }
              }

              complete {
                resp
              }
          }
        }
      }
    }
  }


  implicit val responseMarhaller: Marshaller[LocationInfobox] = Marshaller.of[WikiLocationInfobox](ContentTypes.`application/json`) { (value, contentType, ctx) =>
    val result: String = mapper.writeValueAsString(value)
    ctx.marshalTo(HttpEntity(contentType, result))
  }

I am not able to find a proper way from marshaller and from route via complete function I am not able to make it work.

Could someone more experienced give me a hint? Am I missing some important concept here?

Thx

UPDATE: Error message" Expression of type Future[Object] doesn't conform to expected type ToResponseMarsallable.

2

There are 2 answers

0
jaksky On

This works for me fine taking advantage of MetaMarshallers

          val resp = dataService.ask(GetocationInfoboxData(me, okr)).mapTo[LocationInfoboxDataResult].map(remapInfoboxToResponseObject(_)).map{
            r =>
              r match {
                case None => Left(StatusCodes.NotFound)
                case Some(data) => Right(data)
              }
          }
         complete(resp)
0
4lex1v On

The code looks ok, not sure what doesn't work. Try to rewrite it with Spray directives for futures instead of completing the future itself:

val locationData = dataService.ask(GetocationInfoboxData(me,okr)).mapTo[LocationInfoboxDataResult]

onSuccess(locationData.map(remapInfoboxToResponseObject)) {
  case None => complete(StatusCodes.NotFound)
  case Some(data) => complete(data)
}