Created
January 26, 2015 16:02
-
-
Save edgarmueller/14b426671c07fa6be6ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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