Spray - Building a website

Published 2014-10-27 on Farid Zakaria's Blog

Spray what?

So for my current ongoing project we've been using the excellent Play! Framework; which although primarily designed for websites we used it for an API WebService. So I figure I'd do the opposite with Spray. Spray is a http framework for building web services on top of Akka actors. The next few posts will probably be around some patterns I did in getting a MVP Login demo that accepts UserPassword or OAuth[2] providers.

The following is the specific commit which I believe I've achieved enough of an MVP if you'd like to later browse how its done.

Composing Routes

All the examples on the Spray website show the DSL for the Routes in a single class however I found this to be confusing and exploded to be too large. There are two options people have discussed when composing routes:

  1. Create multiple HttpService actors. Have the main actor forward the RequestContext to other actors based on some route prefix
  2. Use a trait to easily compose the routes that will be given to the runRoute method of the single HttpActor

Although option (2) sounds less `everything on Akka` ideal, it was the option I chose as I found it very easy to bootstrap and the results were fantastic.

trait Routable {
  def route: Route
}

object StaticRouter extends Routable {
  override def route: Route = {
    pathPrefix("static") {
      path(RestPath) { path =>
        getFromResource(s"public/$path")
      }
    }
  }
}

class ApiActor extends HttpServiceActor with ActorLogging {

  def receive = runRoute(
    StaticRouter.route
      ~
    LoginRouter.route
  )
}