Vikas Naidu
Vikas Naidu

Reputation: 320

Akka Http return different type of response based on Accept header

I'm novice to scala and Akka-Http. Experimenting Akka-Http for writing rest services. I have to return json or protobuf based on the Accept header.

 optionalHeaderValueByName("Accept"){ contentType =>
  if(contentType == Some(protoEncode)) {
    complete {
      NewsService.getNewsList().map {
        case stories: List[Story] =>    HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray))
      }
    }
  } else {
      complete {
        NewsService.getNewsList().map {
          case stories: List[Story] => StoryList(stories)
          }
        }
  }

As you can see the code repetition is happening can anyone suggest what could be the best way to optimise and generalise design to avoid such situation.

Upvotes: 2

Views: 498

Answers (2)

Vikas Naidu
Vikas Naidu

Reputation: 320

Figured it out.

optionalHeaderValueByName("Accept") { contentType =>
   onSuccess(NewsService.getNewsList()) {
       case stories: List[Story] => contentType match {
           case Some(protoEncodingString) => complete(HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray)))
           case  _=> complete(StoryList(stories))

         }
     }
}

Upvotes: 1

Daenyth
Daenyth

Reputation: 37431

The simplest way is to move the check inside the body.

optionalHeaderValueByName("Accept"){ contentType =>
      complete {
        NewsService.getNewsList().map {
          case stories: List[Story] =>
            if(contentType == Some(protoEncode)) {
              HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray))
            } else
              StoryList(stories)
        }  
      }
  }

Upvotes: 1

Related Questions