patternMinor
Return different type of response based on Accept header
Viewed 0 times
headerreturnresponseaccepttypedifferentbased
Problem
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.
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?
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?
Solution
I don't know Akka-Http API well enough, but it looks like the
It seems that it is a bit too deeply nested, but at least there is no repetition on
if condition is misplaced. I think that it can be substituted with a matcher under case stories:optionalHeaderValueByName("Accept") { contentType =>
complete {
NewsService.getNewsList().map {
case stories: List[Story] => {
contentType match {
case Some(protoEncode) =>
HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray))
case None => StoryList(stories)
}
}
}
}
}It seems that it is a bit too deeply nested, but at least there is no repetition on
NewsService.getNewsList().map.Code Snippets
optionalHeaderValueByName("Accept") { contentType =>
complete {
NewsService.getNewsList().map {
case stories: List[Story] => {
contentType match {
case Some(protoEncode) =>
HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray))
case None => StoryList(stories)
}
}
}
}
}Context
StackExchange Code Review Q#113501, answer score: 2
Revisions (0)
No revisions yet.