I'm a novice to Scala and Akka-Http and am experimenting with 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 the design to avoid such a situation?