本文整理汇总了Scala中reactivemongo.bson.BSONDocumentReader类的典型用法代码示例。如果您正苦于以下问题:Scala BSONDocumentReader类的具体用法?Scala BSONDocumentReader怎么用?Scala BSONDocumentReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BSONDocumentReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: User
//设置package包名称以及导入依赖的类
package models
import akka.actor.FSM.->
import play.api.data.validation.Constraints._
import play.api.data.format.Formats._
import reactivemongo.bson.{BSONDocumentReader, BSONDocument, BSONDocumentWriter, BSONObjectID}
import play.api.data.{Form, Mapping}
import play.api.data.Forms._
import reactivemongo.bson._
case class User(id:Option[BSONObjectID], user:String,password:String)
object User{
val fldId = "_id"
val fldName = "user"
val fldPassword = "password"
implicit object UserWriter extends BSONDocumentWriter[User]{
def write(user:User):BSONDocument = BSONDocument(
fldId -> user.id.getOrElse(BSONObjectID.generate),
fldName -> user.user,
fldPassword -> user.password
)
}
implicit object UserReader extends BSONDocumentReader[User]{
def read(doc:BSONDocument):User = User(
doc.getAs[BSONObjectID](fldId),
doc.getAs[String](fldName).getOrElse(""),
doc.getAs[String](fldPassword).getOrElse("")
)
}
val form = Form(
mapping(
fldId -> optional(of[String] verifying pattern(
"""[a-fA-F0-9]{24}""".r,
"constraint.objectId",
"error.objectId")),
fldName -> nonEmptyText,
fldPassword -> nonEmptyText){ (id,user,password) =>
User(
id.map(BSONObjectID(_)) ,user,password
)
}{user => Some(user.id.map(_.stringify), user.user, user.password)}
)
}
示例2: ReactivemongoProvider
//设置package包名称以及导入依赖的类
package com.evojam.reactivemongo
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.api.MongoDriver
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter}
import com.evojam.Collection
object ReactivemongoProvider {
def apply[T](dbName: String, collectionName: String)(implicit reader: BSONDocumentReader[T], writer: BSONDocumentWriter[T]): Collection[T] = {
val driver = new MongoDriver
val connection = driver.connection(Seq("localhost"))
val db = connection(dbName)
val collection = db(collectionName)
new ReactivemongoCollection[T](driver, collection, reader, writer)
}
def apply[T](implicit r: BSONDocumentReader[T], w: BSONDocumentWriter[T]): Collection[T] = apply[T]("test", "mongo-driver-benchmarks")
}
示例3: StringMapFormatter
//设置package包名称以及导入依赖的类
package com.evojam.documents
import collection.JavaConversions._
import org.bson.Document
import reactivemongo.bson.{BSONString, BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import com.evojam.driver.DocumentFormat
object StringMapFormatter {
implicit object Handler extends BSONDocumentReader[Map[String, String]] with BSONDocumentWriter[Map[String, String]] {
override def read(bson: BSONDocument): Map[String, String] =
bson.elements.map({case (key, value) => (key, value.asInstanceOf[BSONString].as[String])}).toMap
override def write(t: Map[String, String]): BSONDocument =
BSONDocument(t.toStream.map({case (k,v) => (k, BSONString(v))}))
}
implicit object javaFmt extends DocumentFormat[Map[String, String]] {
override def writes(a: Map[String, String]) = {
val doc = new Document()
a foreach {
case (k, v) => doc.append(k, v)
}
doc
}
override def reads(doc: Document): Map[String, String] =
doc.keySet().map(key => (key, doc.getString(key))).toMap
}
}
示例4: NestedDoc
//设置package包名称以及导入依赖的类
package com.evojam.documents
import org.bson.Document
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import com.evojam.driver.DocumentFormat
case class NestedDoc(name: String, _id: String, left: Option[NestedDoc], right: Option[NestedDoc])
object NestedDoc {
implicit object NestedDocHandler extends BSONDocumentReader[NestedDoc] with BSONDocumentWriter[NestedDoc]{
override def read(bson: BSONDocument): NestedDoc = {
val left = bson.get("left").map(t => read(t.asInstanceOf[BSONDocument]))
val right = bson.get("right").map(t => read(t.asInstanceOf[BSONDocument]))
NestedDoc(bson.getAs[String]("name").get, bson.getAs[String]("_id").get, left, right)
}
override def write(t: NestedDoc): BSONDocument = {
BSONDocument("_id" -> t._id, "name" -> t.name)
.add("left" -> t.left.map(write))
.add("right" -> t.right.map(write))
}
}
implicit val javaFormat = new DocumentFormat[NestedDoc] {
override def writes(a: NestedDoc): Document = {
val doc = new Document("name", a.name)
a.left.foreach(t => doc.append("left", writes(t)))
a.right.foreach(t => doc.append("right", writes(t)))
doc.append("_id", a._id)
}
override def reads(doc: Document): NestedDoc = {
val left = Option(doc.get[Document]("left", classOf[Document])).map(reads)
val right = Option(doc.get[Document]("right", classOf[Document])).map(reads)
NestedDoc(doc.getString("name"), doc.getString("_id"), left, right)
}
}
}
示例5: findAll
//设置package包名称以及导入依赖的类
package com.jjabuk.bookstore.catalog
import com.jjabuk.bookstore.catalog.protocols.CatalogueProtocol.{Book, BooksFound}
import com.jjabuk.bookstore.persistence.MongoDb
import org.slf4j.LoggerFactory
import reactivemongo.api.ReadPreference
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONObjectID}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{ExecutionContext, Future}
trait BookQueries {
def findAll(implicit ec: ExecutionContext): Future[BooksFound]
def findByUuid(uuid: String)(implicit ec: ExecutionContext): Future[Option[BooksFound]]
}
object MongoBookQueries extends BookQueries with MongoDb {
def logger = LoggerFactory.getLogger(this.getClass)
def books: Future[BSONCollection] = database map (_.collection("books"))
implicit def bookReader = new BSONDocumentReader[Book] {
def read(doc: BSONDocument): Book =
Book(
uuid = doc.getAs[BSONObjectID]("_id").get.stringify,
isbn = doc.getAs[String]("isbn").get,
title = doc.getAs[String]("title").get,
review = doc.getAs[String]("review"),
publisher = doc.getAs[String]("publisher")
)
}
def findAll(implicit ec: ExecutionContext): Future[BooksFound] = {
logger.debug(s"Find all books")
books flatMap {
_.find(BSONDocument()).cursor[Book](ReadPreference.Primary).collect[List]()
} map (books => BooksFound(books))
}
def findByUuid(uuid: String)(implicit ec: ExecutionContext): Future[Option[BooksFound]] = {
logger.debug(s"Find a book by uuid=$uuid")
val selector = BSONDocument("_id" -> BSONObjectID.parse(uuid).get)
books
.flatMap(_.find(selector).one[Book])
.map {
case Some(book) => Some(BooksFound(List(book)))
case _ => Option.empty[BooksFound]
}
}
}
示例6: findOneOrCreate
//设置package包名称以及导入依赖的类
package com.aluxian.susucatbot
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, Macros}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success, Try}
package object mongo {
def findOneOrCreate(collection: BSONCollection)
(userQuery: BSONDocument, getNewDoc: => Future[MongoUser]): Future[MongoUser] = {
implicit def mongoEntityWriter: BSONDocumentWriter[MongoEntity] = Macros.writer[MongoEntity]
implicit def mongoThoughtWriter: BSONDocumentWriter[MongoThought] = Macros.writer[MongoThought]
implicit def mongoMessageWriter: BSONDocumentWriter[MongoMessage] = Macros.writer[MongoMessage]
implicit def mongoUserWriter: BSONDocumentWriter[MongoUser] = Macros.writer[MongoUser]
implicit def mongoEntityReader: BSONDocumentReader[MongoEntity] = Macros.reader[MongoEntity]
implicit def mongoThoughtReader: BSONDocumentReader[MongoThought] = Macros.reader[MongoThought]
implicit def mongoMessageReader: BSONDocumentReader[MongoMessage] = Macros.reader[MongoMessage]
implicit def mongoUserReader: BSONDocumentReader[MongoUser] = Macros.reader[MongoUser]
val p = Promise[MongoUser]()
collection.find(userQuery).one[MongoUser].onComplete {
case Success(docOpt) =>
if (docOpt.isDefined) {
p.complete(Try(docOpt.get))
} else {
getNewDoc.onComplete {
case Success(newDocOpt) =>
collection.insert(newDocOpt).onComplete { r =>
collection.find(userQuery).one[MongoUser]
.onComplete {
case Success(docOpt2) =>
val mongoUser = docOpt2.get
p.complete(Try(mongoUser))
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
}
case Failure(ex) => p.failure(ex)
}
p.future
}
}
示例7: Order
//设置package包名称以及导入依赖的类
package models
import reactivemongo.bson.{BSONDocument, BSONDocumentReader}
case class Order(orderID: Int, accountId: String, date: String, time: String, orderStatus: String, paymentMethod: String, orderLines: Array[OrderLine], totalPrice: Double, rating: Int) {}
object Order {
implicit object OrderReader extends BSONDocumentReader[Order] {
def read(doc: BSONDocument): Order =
Order(
doc.getAs[Int]("orderID").get,
doc.getAs[String]("accountID").get,
doc.getAs[String]("date").get,
doc.getAs[String]("time").get,
doc.getAs[String]("orderStatus").get,
doc.getAs[String]("paymentMethod").get,
doc.getAs[Array[OrderLine]]("orderLines").get,
doc.getAs[Double]("totalPrice").get,
doc.getAs[Int]("rating").get
)
}
}
示例8: Product
//设置package包名称以及导入依赖的类
package models
import reactivemongo.bson.{BSONDocument, BSONDocumentReader}
case class Product(itemID: String, product: String, images: Array[String], category: Array[String], description: String, var stock: Int, price: Double) {
def hasXAvailable(x: Int): Boolean = {
this.stock >= x
}
// URL: String
def decrementStock(quantity: Int): Unit = {
//Add stock validation here?
stock = stock - quantity
}
def incrementStock(quantity: Int): Unit = {
//Add stock validation here?
stock += quantity
}
}
object Product {
implicit object productReader extends BSONDocumentReader[Product] {
def read(doc: BSONDocument): Product =
Product(
doc.getAs[String]("itemID").get,
doc.getAs[String]("Product").get,
doc.getAs[Array[String]]("images").get,
doc.getAs[Array[String]]("Category").get,
doc.getAs[String]("Description").get,
doc.getAs[Int]("Stock").get,
doc.getAs[Double]("price").get
)
}
}
示例9: MongoUserRepository
//设置package包名称以及导入依赖的类
package com.example.graphql.service
import reactivemongo.bson.BSONDocumentReader
import reactivemongo.bson.BSONDocumentWriter
import reactivemongo.bson.Macros
import reactivemongo.api.Cursor
import reactivemongo.api.MongoConnection
import reactivemongo.api.MongoDriver
import reactivemongo.api.DefaultDB
import com.example.graphql.model.User
import com.example.graphql.model.Role
import com.example.graphql.model.Address
import java.time.LocalDateTime
import java.util.Locale
import scala.concurrent.Future
class MongoUserRepository extends Repository {
import scala.concurrent.ExecutionContext.Implicits.global
import reactivemongo.bson._
val mongoUri = "mongodb://localhost:27017/mydb?authMode=scram-sha1"
val connection = MongoConnection.parseURI(mongoUri).map(MongoDriver().connection(_))
val futureConnection = Future.fromTry(connection)
def db: Future[DefaultDB] = futureConnection.flatMap(_.database("mydb"))
def collection = db.map(_.collection("users"))
implicit def addressWriter: BSONDocumentWriter[Address] = Macros.writer[Address]
implicit def addressReader: BSONDocumentReader[Address] = Macros.reader[Address]
implicit def userWriter: BSONDocumentWriter[User] = Macros.writer[User]
implicit def userReader: BSONDocumentReader[User] = Macros.reader[User]
def findAll(fields: Seq[String]): Future[Seq[User]] = collection.flatMap(
_.find(document())
.projection(fields.foldLeft(document())((doc, field) => doc.merge(field -> BSONInteger(1))))
.cursor[User]()
.collect(Int.MaxValue, Cursor.FailOnError[Seq[User]]())
)
def findById(id: Long): Future[Option[User]] = collection.flatMap(
_.find(document("id" -> BSONLong(id))).one[User]
)
def addUser(email: String, firstName: Option[String], lastName: Option[String], roles: Seq[Role.Value]): Future[User] = {
val user = User(BSONObjectID.generate().time, email, Some(LocalDateTime.now()), firstName, lastName, Some(roles), Some(false), None)
collection.flatMap(_.insert(user).map(_ => user))
}
def activateById(id: Long): Future[Option[User]] = collection.flatMap(
_.findAndUpdate(document("id" -> BSONLong(id)), document("$set" -> document("active" -> BSONBoolean(true))), fetchNewObject = true)
.map(_.result[User])
)
}
示例10: GalleryCommentEntity
//设置package包名称以及导入依赖的类
package com.rozilo.ussemble.models.db
import java.util.{Calendar, Date}
import com.rozilo.ussemble.models.api.GalleryCommentProtocol.GalleryComment
import io.circe.generic.JsonCodec
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter, BSONObjectID, BSONString}
import io.circe._
import io.circe.generic.semiauto._
case class GalleryCommentEntity(id: BSONObjectID = BSONObjectID.generate,
body: String,
activity_id: BSONObjectID,
sender_id: BSONObjectID,
var read_by: Option[List[String]] = Some(List()),
createdAt: Option[Date] = Some(Calendar.getInstance.getTime),
updatedAt: Option[Date] = Some(Calendar.getInstance.getTime))
object GalleryCommentEntity {
implicit def toGalleryCommentEntity(comment: GalleryComment): GalleryCommentEntity = GalleryCommentEntity(body = comment.body,
activity_id = BSONObjectID.parse(comment.activity_id).get, sender_id = BSONObjectID.parse(comment.sender_id).get)
import io.circe._
import io.circe.syntax._
import io.circe.generic.auto._
// implicit val jsonEncoder = Encoder[GalleryCommentEntity]
// implicit val jsonDecoder = Decoder[GalleryCommentEntity]
implicit object GalleryCommentBSONReader extends BSONDocumentReader[GalleryCommentEntity] {
def read(doc: BSONDocument): GalleryCommentEntity =
GalleryCommentEntity(
id = doc.getAs[BSONObjectID]("_id").get,
body = doc.getAs[String]("body").get,
activity_id = doc.getAs[BSONObjectID]("activity_id").get,
sender_id = doc.getAs[BSONObjectID]("sender_id").get,
read_by = doc.getAs[List[String]]("read_by")
)
}
implicit object GalleryCommentBSONWriter extends BSONDocumentWriter[GalleryCommentEntity] {
def write(commentEntity: GalleryCommentEntity): BSONDocument =
BSONDocument(
"_id" -> commentEntity.id,
"body" -> BSONString(commentEntity.body),
"activity_id" -> commentEntity.activity_id,
"sender_id" -> commentEntity.sender_id,
"read_by" -> commentEntity.read_by,
"created_at" -> commentEntity.createdAt,
"updated_at" -> commentEntity.updatedAt
)
}
}
示例11: isDefined
//设置package包名称以及导入依赖的类
package models
import models.Game._
import reactivemongo.bson.{BSONDocument, BSONDocumentReader, BSONDocumentWriter}
import scala.collection.JavaConverters._
sealed trait Game {
def isDefined: Boolean
def id: GameId
def iconUrl: String
def logoUrl: String
//def cypher = s""":Game {id: "${id}", name: "$toString", imageUrl: "$imageUrl", isDefined: "$isDefined"}"""
}
case class SomeGame(id: GameId, name: String, iconUrl: String, logoUrl: String) extends Game {
override def toString: String = name
override def isDefined: Boolean = true
}
case object NoGame extends Game {
override def id = ""
override def toString: String = "Nothing"
override def isDefined: Boolean = false
override def iconUrl: String = defaultImageUrl
override def logoUrl = defaultImageUrl
}
object Game {
implicit def ordering: Ordering[Game] = Ordering.by(g => (g.isDefined, g.toString))
def apply(id: GameId, name: String, imageUrl: String, logoUrl: String): Game = {
if (id == null || id == "" || name == null || name == "") { NoGame }
else if (imageUrl == null || imageUrl.isEmpty || logoUrl == null || logoUrl.isEmpty) {
SomeGame(id, name, defaultImageUrl, defaultImageUrl)
} else { SomeGame(id, name, imageUrl, logoUrl) }
}
def fromApiModel(g: com.lukaspradel.steamapi.data.json.ownedgames.Game): Game = {
g.getAdditionalProperties.asScala.foreach(t => println(s"additionalprop: $t"))
apply(g.getAppid.toString, g.getName, g.getImgIconUrl, g.getImgLogoUrl)
}
val defaultImageUrl = "placeholder.png"
type GameId = String
implicit object Writer extends BSONDocumentWriter[Game] {
def write(game: Game): BSONDocument = BSONDocument(
"isDefined" -> game.isDefined,
"id" -> game.id,
"name" -> game.toString,
"iconUrl" -> game.iconUrl,
"logoUrl" -> game.logoUrl
)
}
implicit object Reader extends BSONDocumentReader[Game] {
override def read(bson: BSONDocument): Game = apply(
bson.getAs[String]("id").get,
bson.getAs[String]("name").get,
bson.getAs[String]("iconUrl").get,
bson.getAs[String]("logoUrl").get
)
}
}
示例12: id
//设置package包名称以及导入依赖的类
package models
import com.mohiva.play.silhouette.api.Identity
import com.mohiva.play.silhouette.impl.providers.SocialProfile
import reactivemongo.bson.{ BSONDocument, BSONDocumentReader, BSONDocumentWriter, BSONNumberLike }
trait ServiceProfile extends Identity with SocialProfile {
type Self <: ServiceProfile
import models.ServiceProfile._
def id: ServiceUserId
def service: String
def visible: Boolean
def displayName: String
def avatarUrl: String
def profileState: ProfileState
def isInGame: Boolean
def currentlyPlaying: Game
def isRegistered: Boolean
def register: Self
override def equals(obj: scala.Any): Boolean = obj match {
case s: ServiceProfile => s.id == id && s.service == service
case _ => false
}
}
object ServiceProfile {
implicit def ordering: Ordering[ServiceProfile] = Ordering.by { p: ServiceProfile => { (p.visible, p.currentlyPlaying, p.profileState, p.displayName) } }
implicit def ordering2: Ordering[ProfileState] = Ordering.by(s => s.priority)
type ServiceUserId = String
sealed trait ProfileState {
def priority: Int
}
case object Online extends ProfileState { override def priority = 4 }
case object Offline extends ProfileState { override def priority = 20 }
case object Busy extends ProfileState { override def priority = 8 }
case object Away extends ProfileState { override def priority = 6 }
case object Snooze extends ProfileState { override def priority = 10 }
case object LookingToTrade extends ProfileState { override def priority = 2 }
case object LookingToPlay extends ProfileState { override def priority = 0 }
implicit object ProfileStateWriter extends BSONDocumentWriter[ProfileState] {
def write(state: ProfileState): BSONDocument = BSONDocument("code" -> stateCode(state))
}
implicit object ProfileStateReader extends BSONDocumentReader[ProfileState] {
override def read(bson: BSONDocument): ProfileState = profileStateFactory(bson.getAs[BSONNumberLike]("code").get.toInt)
}
def stateCode(state: ProfileState): Int = state match {
case Offline => 0
case Online => 1
case Busy => 2
case Away => 3
case Snooze => 4
case LookingToTrade => 5
case LookingToPlay => 6
}
}
示例13: service
//设置package包名称以及导入依赖的类
package models
import com.lukaspradel.steamapi.data.json.playersummaries.Player
import models.ServiceProfile.ProfileState
import reactivemongo.bson.{ BSONDocument, BSONDocumentReader, BSONDocumentWriter }
trait SteamProfile extends ServiceProfile {
override type Self = SteamProfile
def service: String = "Steam"
}
trait SteamProfileFactory {
def apply(profileData: Player): SteamProfile
}
object SteamProfile {
implicit object Writer extends BSONDocumentWriter[SteamProfile] {
def write(profile: SteamProfile): BSONDocument = BSONDocument(
"id" -> profile.id,
"service" -> profile.service,
"visible" -> profile.visible,
"displayName" -> profile.displayName,
"avatarUrl" -> profile.avatarUrl,
"profileState" -> profile.profileState,
"isInGame" -> profile.isInGame,
"currentlyPlaying" -> profile.currentlyPlaying
)
}
implicit object Reader extends BSONDocumentReader[SteamProfile] {
def read(doc: BSONDocument): SteamProfile = {
println("asdfADSFGAA SDFAG")
SteamProfileImpl(
doc.getAs[String]("id").get,
doc.getAs[Boolean]("visible").get,
doc.getAs[String]("displayName").get,
doc.getAs[String]("avatarUrl").get,
doc.getAs[ProfileState]("profileState").get,
doc.getAs[Game]("currentlyPlaying").get,
doc.getAs[Boolean]("isRegistered").get
)
}
}
}
示例14: MongoRepository
//设置package包名称以及导入依赖的类
package io.shedin.crud.mongo
import io.shedin.crud.lib.CrudRepository
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.{DefaultDB, MongoConnection, MongoConnectionOptions, MongoDriver}
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter, document}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
// TODO maybe should just mix in AsyncCrudOperations[T] instead of CrudRepository[T]
abstract class MongoRepository[T]
(databaseName: String)
(implicit writer: BSONDocumentWriter[T], reader: BSONDocumentReader[T], manifest: Manifest[T])
extends CrudRepository[T] {
private lazy val mongoUri = s"mongodb://localhost:27017/$databaseName?authMode=scram-sha1"
private lazy val eventualMongoConnection = Future.fromTry(MongoConnection.parseURI(mongoUri).map(MongoDriver().connection(_)))
private def mongoDatabase: Future[DefaultDB] = eventualMongoConnection.flatMap(_.database(databaseName))
private def mongoCollection = mongoDatabase.map(_.collection[BSONCollection](simpleName(manifest)))
override def create(resource: T): Future[T] =
mongoCollection.flatMap { bsonCollection =>
bsonCollection.insert(resource).map { writeResult =>
if (writeResult.n == 1) resource
else throw new RuntimeException(s"failed to persist resource [$resource]")
}
}
override def read(resourceId: String): Future[Option[T]] = {
mongoCollection.flatMap(_.find(document("id" -> resourceId)).cursor[T]().collect[List]()) map (_.headOption)
}
override def update(resourceId: String, resource: T): Future[Option[T]] = {
mongoCollection.flatMap(_.update(document("id" -> resourceId), resource)) map { updateWriteResult =>
if (updateWriteResult.n == 0) None
else if (updateWriteResult.n == 1) Some(resource)
else throw new RuntimeException("more than one doc updated") // TODO revisit this
}
}
override def update(resourceId: String, updatePayload: String): Future[Option[AnyRef]] = throw new UnsupportedOperationException
override def delete(resourceId: String): Future[Boolean] =
mongoCollection.flatMap(_.remove(document("id" -> resourceId))) map (_.n > 0)
private def simpleName[T](manifest: Manifest[T]): String =
manifest.runtimeClass.getSimpleName.toLowerCase
}
示例15: MongoBSONSearchableRepositorySpec
//设置package包名称以及导入依赖的类
package com.clemble.query
import reactivemongo.api.MongoDriver
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.bson.{BSONDocumentWriter, BSONDocumentReader, BSONDocument}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
class MongoBSONSearchableRepositorySpec extends SearchableRepositorySpec {
implicit val format: BSONDocumentReader[Employee] with BSONDocumentWriter[Employee] = new BSONDocumentReader[Employee] with BSONDocumentWriter[Employee] {
override def write(t: Employee): BSONDocument = BSONDocument(
"name" -> t.name,
"salary" -> t.salary
)
override def read(bson: BSONDocument): Employee =
Employee(
bson.getAs[String]("name").get,
bson.getAs[Int]("salary").get
)
}
override val repo: MongoBSONSearchableRepository[Employee] with ProjectionSupport = new MongoBSONSearchableRepository[Employee] with MongoBSONProjectionSupport[Employee] {
override val collection: BSONCollection = {
SpecificationConstants.db.collection[BSONCollection]("employee_bson")
}
override val queryTranslator: QueryTranslator[BSONDocument, BSONDocument] = new MongoBSONQueryTranslator()
override implicit val f: BSONDocumentReader[Employee] = format
}
override def save(employee: Employee): Boolean = {
val fSave = repo.collection.update(BSONDocument("_id" -> employee.name), format.write(employee), upsert = true)
Await.result(fSave, 1 minute).errmsg.isEmpty
}
override def remove(employee: Employee): Boolean = {
val fRemove = repo.collection.remove(BSONDocument("name" -> employee.name))
Await.result(fRemove, 1 minute).errmsg.isEmpty
}
}