4
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\begingroup\$ Hi and welcome to Code Review. In order to avoid confusion for future readers and invalidating existing answers, if you have found improvements on your own, please post them as an answer. If you have updated your code and would like the (new) code reviewed, please post a follow-up question. \$\endgroup\$
    – Kaz
    Dec 11 '15 at 9:42
  • \$\begingroup\$ Welcome to Code Review! I have rolled back the last edit. Please see what you may and may not do after receiving answers. \$\endgroup\$ Dec 11 '15 at 9:43
2
\$\begingroup\$

I don't know Akka-Http API well enough, but it looks like the 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.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the answer. the way you suggested would work generally. But, akka-http complete method doesn't accept two different return types. I've updated the code please check it out. \$\endgroup\$ Dec 11 '15 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.