• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala ReadPreference类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中reactivemongo.api.ReadPreference的典型用法代码示例。如果您正苦于以下问题:Scala ReadPreference类的具体用法?Scala ReadPreference怎么用?Scala ReadPreference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ReadPreference类的16个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: find

//设置package包名称以及导入依赖的类
package repos

import scala.concurrent.{ExecutionContext, Future}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import play.api.libs.json.{JsObject, Json}
import reactivemongo.api.commands.WriteResult
import play.modules.reactivemongo.ReactiveMongoApi
import javax.inject._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference

trait PostRepo {
	def find() (implicit ec: ExecutionContext): Future[List[JsObject]]

	def select(selector: BSONDocument) (implicit ec: ExecutionContext): Future[Option[JsObject]]

	def update(selector: BSONDocument, update: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]

	def remove(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]

	def save(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]

}

class PostRepoImpl @Inject() (reactiveMongoApi: ReactiveMongoApi) extends PostRepo {
  def collection = reactiveMongoApi.db.collection[JSONCollection]("posts");
  
  override def find() (implicit ec: ExecutionContext): Future[List[JsObject]] = {
    val genericQueryBuilder = collection.find(Json.obj());
    val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary);
    cursor.collect[List]()
  }

  def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
    collection.find(selector).one[JsObject]
  }

  def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(selector,update)
  }

  def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.remove(document)
  }

  def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
  }
  
} 
开发者ID:Rheriel,项目名称:LightHouse,代码行数:52,代码来源:PostRepo.scala


示例2: PlaceController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import models._
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.api.ReadPreference
import reactivemongo.play.json.collection._
import utils.Errors
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}



@Singleton
class PlaceController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {

  def placeFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("place"))

  def create(name: String, location: Location, residents: Seq[Resident] ) = Action.async {
    for {
      places <- placeFuture
      lastError <- places.insert(Place(name, location, residents))
    } yield
      Ok("Mongo LastError: %s".format(lastError))
  }

  def createFromJson = Action.async(parse.json) { request =>
    Json.fromJson[Place](request.body) match {
      case JsSuccess(place, _) =>
        for {
          places <- placeFuture
          lastError <- places.insert(place)
        } yield {
          Logger.debug(s"Successfully inserted with LastError: $lastError")
          Created("Created 1 place")
        }
      case JsError(errors) =>
        Future.successful(BadRequest("Could not build a place from the json provided. " + Errors.show(errors)))
    }
  }

  def findPlace(name: String) = Action.async {
    val futurePlacesList: Future[List[Place]] = placeFuture.flatMap{
        _.find(Json.obj("name" -> name)).
          cursor[Place](ReadPreference.primary).
          collect[List]()
    }
    futurePlacesList.map { places =>
      Ok(Json.prettyPrint(Json.toJson(places))) }
  }


} 
开发者ID:Yashar78,项目名称:play,代码行数:58,代码来源:PlaceController.scala


示例3: find

//设置package包名称以及导入依赖的类
package repos

import javax.inject.Inject

import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.{ExecutionContext, Future}

trait RepoLike {
  def find()(implicit ec: ExecutionContext): Future[List[JsObject]]

  def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]]

  def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]

  def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]

  def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}

abstract class Repo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends RepoLike {
  val collectionName: String

  override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
    collection.find(Json.obj())
      .cursor[JsObject](ReadPreference.Primary)
      .collect[List](100)
  }

  override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
    collection.find(selector).one[JsObject]
  }

  override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(selector, update)
  }

  def collection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection](collectionName)

  override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.remove(document)
  }

  override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
  }
} 
开发者ID:aphexcx,项目名称:iconoclast-api,代码行数:54,代码来源:Repo.scala


示例4: TranslatorRepositoryImpl

//设置package包名称以及导入依赖的类
package Repositories.implements

import Repositories.TranslatorRepository
import com.google.inject.Inject
import models.Translator
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.{QueryOpts, ReadPreference}
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json.collection.JSONCollection
import utils.Pagination
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}


class TranslatorRepositoryImpl @Inject()(reactiveMongoApi: ReactiveMongoApi) extends TranslatorRepository{
  def collection(implicit ec: ExecutionContext) = reactiveMongoApi.database.map(_.collection[JSONCollection]("translators"))

  override def getAllTranslators(pagination: Pagination, sortField: String)(implicit ec: ExecutionContext): Future[List[JsObject]] = {
    var sort : Int = 1; var getField: String = sortField
    if(sortField.startsWith("-")){
      sort = -1; getField = sortField.drop(1)
    }
    val genericQueryBuilder = collection.map(_.find(Json.obj()).sort(Json.obj(getField -> sort)).options(QueryOpts(pagination.Offset)))
    val cursor = genericQueryBuilder.map(_.cursor[JsObject](ReadPreference.Primary))
    cursor.flatMap(_.collect[List](pagination.Limit))
  }

  override def insertTranslator(translator: Translator)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.flatMap(_.insert(translator))
  }

  override def count()(implicit ec: ExecutionContext): Future[Int] = {
    val count = collection.flatMap(_.count()); count
  }
} 
开发者ID:sopheakreth,项目名称:rest-api-play-scala-mongodb,代码行数:37,代码来源:TranslatorRepositoryImpl.scala


示例5: nearPoint

//设置package包名称以及导入依赖的类
package io.soheila.commons.geospatials

import grizzled.slf4j.Logger
import io.soheila.commons.crud.MongoCRUDDAO
import io.soheila.commons.entities.{ Locatable, Page }
import io.soheila.commons.exceptions.{ ErrorCode, MongoDAOException, MongoExceptionBuilder }
import play.api.libs.json.{ Json, Reads }
import play.modules.reactivemongo.json._
import reactivemongo.api.indexes.Index
import reactivemongo.api.indexes.IndexType.Geo2DSpherical
import reactivemongo.api.{ Cursor, ReadPreference }

import scala.concurrent.{ ExecutionContext, Future }

trait Geospatial[T <: Locatable, ID] {
  self: MongoCRUDDAO[T, ID] =>

  private val logger = Logger[this.type]

  lazy val LocationField = "coordinate"

  lazy val geo2DSphericalIndex = Index(Seq((LocationField, Geo2DSpherical)), Some("geo2DSphericalIdx"))

  
  def nearPoint(lon: Double, lat: Double, minDistance: Double = 1, maxDistance: Double = 10000, page: Int = 0, limit: Int = 100, readPreference: ReadPreference = ReadPreference.primaryPreferred)(implicit ec: ExecutionContext, reads: Reads[T]): Future[Either[MongoDAOException, Page[T]]] = {
    val offset = page * limit

    val totalCount = collection.flatMap(_.count())

    val searchResult = collection.flatMap(_.find(
      Json.obj(
        LocationField -> Json.toJson(Json.obj(
          "$geoNear" -> Json.toJson(Json.obj(
            "$geometry" -> Json.toJson(Json.obj(
              "type" -> "Point",
              "coordinates" -> Json.arr(lon, lat)
            )),
            "$maxDistance" -> Json.toJson(maxDistance),
            "$minDistance" -> Json.toJson(minDistance)
          ))
        ))
      )
    ).cursor[T](readPreference).collect[Seq](limit, Cursor.FailOnError((seq: Seq[T], err) => logger.error("Error finding locations.", err))))

    totalCount.zip(searchResult).map {
      case (total, entities) =>
        Right(Page(entities, page, offset, total))
    }.recover {
      case e => Left(MongoExceptionBuilder.buildException(e))
    }
  }

} 
开发者ID:esfand-r,项目名称:play-reactivemongo-commons,代码行数:54,代码来源:Geospatial.scala


示例6: MongoUserPaymentRepository

//设置package包名称以及导入依赖的类
package com.clemble.loveit.payment.service.repository.mongo

import javax.inject.{Inject, Named}

import akka.stream.Materializer
import akka.stream.scaladsl.Source
import com.clemble.loveit.payment.model.UserPayment
import com.clemble.loveit.payment.service.repository.UserPaymentRepository
import play.api.libs.json.Json
import reactivemongo.api.ReadPreference
import reactivemongo.akkastream.cursorProducer
import reactivemongo.play.json.collection.JSONCollection
import reactivemongo.play.json._

import scala.concurrent.ExecutionContext


case class MongoUserPaymentRepository @Inject()(@Named("user") collection: JSONCollection, implicit val m: Materializer, implicit val ec: ExecutionContext) extends UserPaymentRepository {

  override def find(): Source[UserPayment, _] = {
    val selector = Json.obj()
    val projection = Json.obj("id" -> 1, "balance" -> 1, "chargeAccount" -> 1, "payoutAccount" -> 1, "monthlyLimit" -> 1, "pending" -> 1)
    collection.
      find(selector, projection).
      cursor[UserPayment](ReadPreference.nearest).
      documentSource()
  }

} 
开发者ID:thankyo,项目名称:thank,代码行数:30,代码来源:MongoUserPaymentRepository.scala


示例7: findByUser

//设置package包名称以及导入依赖的类
package com.clemble.loveit.common.mongo

import akka.stream.Materializer
import akka.stream.scaladsl.Source
import com.clemble.loveit.common.model.UserID
import com.clemble.loveit.user.model.UserAware
import com.clemble.loveit.user.service.repository.UserAwareRepository
import play.api.libs.json.{Format, Json}
import reactivemongo.akkastream.cursorProducer
import reactivemongo.api.ReadPreference
import reactivemongo.api.indexes.{Index, IndexType}
import reactivemongo.play.json._
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.ExecutionContext

trait MongoUserAwareRepository[T <: UserAware] extends UserAwareRepository[T] {

  val collection: JSONCollection
  implicit val m: Materializer
  implicit val ec: ExecutionContext
  implicit val format: Format[T]

  MongoSafeUtils.ensureIndexes(
    collection,
    Index(
      key = Seq("user" -> IndexType.Ascending, "created" -> IndexType.Ascending),
      name = Some("user_created_asc")
    ),
    Index(
      key = Seq("user" -> IndexType.Ascending),
      name = Some("user_asc")
    )
  )

  override def findByUser(user: UserID): Source[T, _] = {
    collection.find(Json.obj("user" -> user)).sort(Json.obj("created" -> 1)).cursor[T](ReadPreference.nearest).documentSource()
  }


} 
开发者ID:thankyo,项目名称:thank,代码行数:42,代码来源:MongoUserAwareRepository.scala


示例8: TeamSearchApi

//设置package包名称以及导入依赖的类
package lila.teamSearch

import lila.search._
import lila.team.{ Team, TeamRepo }

import play.api.libs.json._

final class TeamSearchApi(client: ESClient) extends SearchReadApi[Team, Query] {

  def search(query: Query, from: From, size: Size) =
    client.search(query, from, size) flatMap { res =>
      TeamRepo byOrderedIds res.ids
    }

  def count(query: Query) = client.count(query) map (_.count)

  def store(team: Team) = client.store(Id(team.id), toDoc(team))

  private def toDoc(team: Team) = Json.obj(
    Fields.name -> team.name,
    Fields.description -> team.description.take(10000),
    Fields.location -> team.location,
    Fields.nbMembers -> team.nbMembers
  )

  def reset = client match {
    case c: ESClientHttp => c.putMapping >> {
      import play.api.libs.iteratee._
      import reactivemongo.api.ReadPreference
      import reactivemongo.play.iteratees.cursorProducer
      import lila.db.dsl._

      logger.info(s"Index to ${c.index.name}")

      val batchSize = 200
      val maxEntries = Int.MaxValue

      TeamRepo.cursor(
        selector = $doc("enabled" -> true),
        readPreference = ReadPreference.secondaryPreferred
      )
        .enumerator(maxEntries) &>
        Enumeratee.grouped(Iteratee takeUpTo batchSize) |>>>
        Iteratee.foldM[Seq[Team], Int](0) {
          case (nb, teams) =>
            c.storeBulk(teams.toList map (t => Id(t.id) -> toDoc(t))) inject {
              logger.info(s"Indexed $nb teams")
              nb + teams.size
            }
        }
    } >> client.refresh
    case _ => funit
  }
} 
开发者ID:DrNixx,项目名称:line,代码行数:55,代码来源:TeamSearchApi.scala


示例9: EntryRepo

//设置package包名称以及导入依赖的类
package lila.timeline

import lila.db.dsl._
import org.joda.time.DateTime
import reactivemongo.api.ReadPreference
import reactivemongo.bson._

private[timeline] final class EntryRepo(coll: Coll, userMax: Int) {

  import Entry._

  private val projection = $doc("users" -> false)

  def userEntries(userId: String): Fu[List[Entry]] =
    userEntries(userId, userMax)

  def moreUserEntries(userId: String, nb: Int): Fu[List[Entry]] =
    userEntries(userId, nb)

  private def userEntries(userId: String, max: Int): Fu[List[Entry]] =
    coll.find($doc("users" -> userId), projection)
      .sort($sort desc "date")
      .cursor[Entry](ReadPreference.secondaryPreferred)
      .gather[List](max)

  def findRecent(typ: String, since: DateTime, max: Int) =
    coll.find(
      $doc("typ" -> typ, "date" $gt since),
      projection
    ).sort($sort desc "date")
      .cursor[Entry](ReadPreference.secondaryPreferred)
      .gather[List](max)

  def channelUserIdRecentExists(channel: String, userId: String): Fu[Boolean] =
    coll.count($doc(
      "users" -> userId,
      "chan" -> channel,
      "date" $gt DateTime.now.minusDays(7)
    ).some) map (0 !=)

  def insert(e: Entry.ForUsers) =
    coll.insert(EntryBSONHandler.write(e.entry) ++ $doc("users" -> e.userIds)) void
} 
开发者ID:DrNixx,项目名称:line,代码行数:44,代码来源:EntryRepo.scala


示例10: BalanceInfoController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.{Inject, Singleton}

import models.BalanceInfo
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.{Cursor, ReadPreference}

import scala.concurrent.{ExecutionContext, Future}


@Singleton
class BalanceInfoController @Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext)
  extends Controller with MongoController with ReactiveMongoComponents {

  val balances: JSONCollection = db.collection[JSONCollection]("balance_info")

  def get(name: String) = Action.async {
    val balanceCursor: Cursor[BalanceInfo] =
      balances.find(Json.obj("name" -> name)).cursor[BalanceInfo](ReadPreference.primary)
    val balanceFuture: Future[List[BalanceInfo]] = balanceCursor.collect[List]()
    balanceFuture.map { data => Ok(Json.toJson(data)) }
  }

} 
开发者ID:qza,项目名称:balance-service-play,代码行数:30,代码来源:BalanceInfoController.scala


示例11: MongoBillingDetailsRepository

//设置package包名称以及导入依赖的类
package com.lej.customer.infrastructure.persistence

import javax.inject.Inject

import com.lej.customer.domain.model.BillingDetailsRepository
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.{ExecutionContext, Future}

class MongoBillingDetailsRepository @Inject()(reactiveMongoApi: ReactiveMongoApi) extends BillingDetailsRepository {
  def collection = reactiveMongoApi.db.collection[JSONCollection]("billing_details")

  override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
    val genericQueryBuilder = collection.find(Json.obj())
    val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary)
    cursor.collect[List]()
  }

  override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
    collection.find(selector).one[JsObject]
  }

  override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(selector, update)
  }

  override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.remove(document)
  }

  override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
  }
} 
开发者ID:torstenheinrich,项目名称:lej-order-scala,代码行数:41,代码来源:MongoBillingDetailsRepository.scala


示例12: PlaceDAO

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import com.google.common.io.Files
import models.{Place, PlaceData}
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.Files.TemporaryFile
import play.api.libs.json.Json
import play.api.mvc.Controller
import play.api.mvc.MultipartFormData.FilePart
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.commands.WriteResult
import reactivemongo.api.{Cursor, ReadPreference}
import reactivemongo.play.json.collection.JSONCollection

import scala.concurrent.{ExecutionContext, Future}

class PlaceDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)
                         (implicit ec: ExecutionContext)
    extends Controller with MongoController with ReactiveMongoComponents{
  def create(placeData: PlaceData, picture: FilePart[TemporaryFile]): Future[WriteResult] = {
    placesCollection.flatMap(_.insert(Place(placeData.name, placeData.country, placeData.description,
      Files.toByteArray(picture.ref.file))))
  }

  def all(): Future[List[Place]] = placesCollection.flatMap(_.find(Json.obj())
        .cursor[Place](ReadPreference.primaryPreferred).collect[List](Int.MaxValue, Cursor.FailOnError[List[Place]]()))

  def placesCollection: Future[JSONCollection] = database.map(_.collection[JSONCollection]("places"))
}


object PlaceDAO {
  val createPlaceForm = Form(
    mapping(
      "name" -> nonEmptyText,
      "country" -> nonEmptyText,
      "description" -> nonEmptyText
    )(PlaceData.apply)(PlaceData.unapply)
  )
} 
开发者ID:test410,项目名称:picture-gallery,代码行数:45,代码来源:PlaceDAO.scala


示例13: ValorationDAO

//设置package包名称以及导入依赖的类
package dao.impl

import play.api.libs.json.{ JsObject, Json }
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{ BSONObjectID, BSONDocument }
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.bson.{ BSONObjectID, BSONDocument }
import scala.concurrent.{ ExecutionContext, Future }
import dao.TValorationDAO
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.json.BSONDocumentWrites
import play.modules.reactivemongo.json.JsObjectDocumentWriter
import reactivemongo.bson.Producer.nameValue2Producer
import scala.annotation.implicitNotFound

class ValorationDAO(reactiveMongoApi: ReactiveMongoApi) extends TValorationDAO {
  // BSON-JSON conversions
  import play.modules.reactivemongo.json._

  protected def collection =
    reactiveMongoApi.db.collection[JSONCollection]("valorations")
    
  def uuid = java.util.UUID.randomUUID.toString

  def find()(implicit ec: ExecutionContext): Future[List[JsObject]] =
    collection.find(Json.obj()).cursor[JsObject](ReadPreference.Primary).collect[List]()
    
  def findBySpot(spotId: String)(implicit ec: ExecutionContext): Future[List[JsObject]] =
    collection.find(BSONDocument("spot_id" -> spotId)).cursor[JsObject]().collect[List]()
    
  def findById(genId: String)(implicit ec: ExecutionContext): Future[Option[JsObject]] =
    collection.find(BSONDocument("_id" -> genId)).one[JsObject]
  
  def findById2(genId: String)(implicit ec: ExecutionContext): Future[Option[BSONDocument]] =
    collection.find(BSONDocument("_id" -> genId)).one[BSONDocument]
    
  def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] =
    collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)

} 
开发者ID:ElComite,项目名称:placesmapper_back,代码行数:42,代码来源:ValorationDAO.scala


示例14: find

//设置package包名称以及导入依赖的类
package repos

import javax.inject.Inject

import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}

import scala.concurrent.{ExecutionContext, Future}

trait ApiRepo {
  def find()(implicit ec: ExecutionContext): Future[List[JsObject]]

  def save(selector: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}

class MongoApiRepo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends ApiRepo {

  def collection = reactiveMongoApi.db.collection[JSONCollection]("users")

  override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
    val genericQueryBuilder = collection.find(Json.obj())
    val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary)
    cursor.collect[List]()
  }

  override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
    collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
  }

} 
开发者ID:Jagordon,项目名称:play-api,代码行数:36,代码来源:api.scala


示例15: HealthcheckController

//设置package包名称以及导入依赖的类
package controller.admin

import com.google.inject.{Inject, Singleton}
import conf.{BuildInfo, BuildInformation}
import db.DbConnection
import logging.MdcExecutionContext.Implicit.defaultContext
import play.api.mvc.{Action, Controller}
import reactivemongo.api.commands.Command
import reactivemongo.api.{BSONSerializationPack, FailoverStrategy, ReadPreference}
import reactivemongo.bson.BSONDocument

@Singleton
class HealthcheckController @Inject() (buildInfo: BuildInfo) extends Controller {

  def check() = Action.async {
    val runner = Command.run(BSONSerializationPack, FailoverStrategy())
    runner.apply(DbConnection.db, runner.rawCommand(BSONDocument("ping" -> 1))).one(ReadPreference.primaryPreferred) map {
      res =>
        if (res.getAs[Double]("ok").getOrElse(0) == 1.0)
          Ok(healthyMessage(buildInfo.fromApplicationConfig))
        else
          InternalServerError("unhealty!")
    }
  }

  private def healthyMessage(buildInfo: Option[BuildInformation]) = {
    val buildNumber = buildInfo.map(_.buildNumber).getOrElse("[not available]")
    s"""|healthy!
        |build-number: $buildNumber""".stripMargin
  }
} 
开发者ID:UKHomeOffice,项目名称:submission-service,代码行数:32,代码来源:HealthcheckController.scala


示例16: EncryptionController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.api.ReadPreference
import reactivemongo.play.json._
import reactivemongo.play.json.collection._

import scala.concurrent.{ExecutionContext, Future}

class EncryptionController @Inject() (val reactiveMongoApi: ReactiveMongoApi)(implicit ec: ExecutionContext)
  extends Controller with MongoController with ReactiveMongoComponents {

  def index = Action {
    Ok(views.html.encrypt())
  }

  def upload = Action.async(parse.json) { request =>
    val json = request.body.asInstanceOf[JsObject]
    photosCollection
      .flatMap(_.update(Json.obj("filename" -> json.value("filename")), json, upsert = true))
      .map(writeResult => Ok(s"Upload result: $writeResult"))
  }

  def download(filename: String) = Action.async {
    photosCollection
      .flatMap(findOneByFilename(filename))
      .map(Ok(_))
  }

  def gallery = Action {
    Ok(views.html.gallery())
  }

  def getFilenames = Action.async {
    photosCollection
      .flatMap(getAllFileNames)
      .map(res => Ok(Json.toJson(res)))
  }

  private def findOneByFilename(filename: String)(photos: JSONCollection): Future[JsObject] =
    photos.find(Json.obj("filename" -> filename))
      .cursor[JsObject](ReadPreference.secondaryPreferred)
      .collect[List]()
      .map(_.head)

  private def getAllFileNames(photos: JSONCollection): Future[List[JsObject]] =
    photos.find(Json.obj(), Json.obj("filename" -> 1))
      .cursor[JsObject](ReadPreference.secondaryPreferred)
      .collect[List]()

  private def photosCollection: Future[JSONCollection] =
    database.map(_.collection[JSONCollection]("photos"))
} 
开发者ID:zoltanmaric,项目名称:slike,代码行数:58,代码来源:EncryptionController.scala



注:本文中的reactivemongo.api.ReadPreference类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala UnsafeMapData类代码示例发布时间:2022-05-23
下一篇:
Scala Put类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap