Akka Http returns different response types based on the Accept header

advertisements

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.


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)
        }
      }
  }