Skip to content

Instantly share code, notes, and snippets.

@edgarmueller
Last active August 29, 2015 14:14
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/8ed5f4c2ad6c63e44202 to your computer and use it in GitHub Desktop.
Save edgarmueller/8ed5f4c2ad6c63e44202 to your computer and use it in GitHub Desktop.
package rest.spray.service
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
object Db {
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
val db = connection("plugin")
val collection = db("acoll")
def getAll(): Future[List[Post]] ={
val query = BSONDocument(
"likes" -> BSONDocument(
"$gt" -> 27))
collection.find(query).cursor[Post].collect[List]()
}
}
case class Post(id: BSONObjectID, likes: Long, message: String, object_id: String, shares: Long)
object Post {
implicit val reader: BSONDocumentReader[Post] = Macros.reader[Post]
}
class RestServiceActor extends Actor with HttpService {
implicit def actorRefFactory = context
def receive = runRoute(route1)
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")
}
}
object PostJsonProtocol extends DefaultJsonProtocol {
implicit val format = jsonFormat5(Post.apply)
}
import PostJsonProtocol._
val route1 = path("posts") {
onComplete(Db.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