Skip to content

Instantly share code, notes, and snippets.

@edgarmueller
Created January 26, 2015 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edgarmueller/14b426671c07fa6be6ae to your computer and use it in GitHub Desktop.
Save edgarmueller/14b426671c07fa6be6ae to your computer and use it in GitHub Desktop.
package com.example
import akka.actor.Actor
import reactivemongo.api.MongoDriver
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONObjectID, Macros}
import spray.httpx.SprayJsonSupport._
import spray.json._
import spray.routing._
import scala.concurrent.Future
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global
import com.example.mongo.services.Mongo
import com.example.model.Post
// we don't implement our route structure directly in the service actor because
// we want to be able to test it independently, without having to spin up an actor
class MyServiceActor extends Actor with MyService {
// the HttpService trait defines only one abstract member, which
// connects the services environment to the enclosing actor or test
def actorRefFactory = context
// this actor only runs our route, but you could add
// other things here, like request stream processing
// or timeout handling
def receive = runRoute(route1)
}
// top level
object PostJsonProtocol extends DefaultJsonProtocol {
implicit object BSONObjectIdProtocol extends RootJsonFormat[BSONObjectID] {
override def write(obj: BSONObjectID): JsValue = JsString(obj.stringify)
override def read(json: JsValue): BSONObjectID = json match {
case JsString(id) => BSONObjectID.parse(id) match {
case Success(validId) => validId
case _ => deserializationError("Invalid BSON Object Id")
}
case _ => deserializationError("BSOn Object Id expected")
}
}
implicit val format = jsonFormat5(Post.apply)
}
// this trait defines our service behavior independently from the service actor
trait MyService extends HttpService {
import PostJsonProtocol._ // is in scope now
val mongoService = new Mongo
val route1 = path("posts") {
onComplete(mongoService.getAll()) {
case Success(value) => complete(value)
case Failure(ex) => complete(ex.getMessage)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment