Reputation: 320
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
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
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