0

How can I complete akka-http response with different types based on future response? I am trying to do something like

implicit val textFormat = jsonFormat1(Text.apply)
implicit val userFormat = jsonFormat2(User.apply)
 path(Segment) { id =>
              get {
                complete {
                  (fooActor ? GetUser(id)).map {
                    case n: NotFound => Text("Not Found")
                    case u: User => u
                  }
                }

              }
            }

but I am getting

type mismatch , expected: ToResponseMarshable , actual Futue[Product with Serializable ]
igx
  • 4,101
  • 11
  • 43
  • 88
  • I think it is because it does not know how to unmarshall the custom `User` class. You have to define one. See the Unmarshaller section and links off this page: http://doc.akka.io/docs/akka-http/current/java/http/routing-dsl/marshalling.html – Brian Jan 04 '17 at 16:41
  • @brian I don't think so since if I reply with User on both cases then it is OK, also not that I have unmarshaller in scope for User – igx Jan 04 '17 at 16:46

1 Answers1

3

You could use the onComplete directive:

get {
  path(Segment) { id =>
    onComplete(fooActor ? GetUser(id)) {
      case Success(actorResponse) => actorResponse match {
        case _ : NotFound => complete(StatusCodes.NotFound,"Not Found")
        case u : User => complete(StatusCodes.OK, u)
      }
      case Failure(ex) => complete(StatusCodes.InternalServerError, "bad actor")
    }
  }
}
Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125