当前位置: 首页>>代码示例>>Scala>>正文


Scala EitherT类代码示例

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


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

示例1: ServiceOp

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

import cats.data.EitherT

package object algebra {
  import cats._

  sealed abstract class ServiceOp[A] extends Product with Serializable
  final case class FetchUser(userId: Long) extends ServiceOp[TimeoutException Either User]
  final case class FetchAddress(addressId: Long) extends ServiceOp[TimeoutException Either Address]

  type ServiceIO[A] = cats.free.Free[ServiceOp, A]

  object ServiceOps {
    def fetchUser(userId: Long): ServiceIO[TimeoutException Either User] =
      cats.free.Free.liftF(FetchUser(userId))

    def fetchAddress(addressId: Long): ServiceIO[TimeoutException Either Address] =
      cats.free.Free.liftF(FetchAddress(addressId))
  }

  def interpreter[M[_] : Effect : Monad ](implicit ins: ?service[M]): ServiceOp ~> M =
    new (ServiceOp ~> M) {
      override def apply[A](fa: ServiceOp[A]): M[A] = {
        val result = fa match {
          case FetchUser(userId) => (ins fetchUser userId)
          case FetchAddress(addressId) => (ins fetchAddress addressId)
        }
        result.asInstanceOf[M[A]]
      }
    }

  def fetchBoth(userId: Long): ServiceIO[TimeoutException Either (User, Address)] =
    (for {
      user <-  EitherT[ServiceIO, TimeoutException, User](ServiceOps.fetchUser(userId))
      address <- EitherT[ServiceIO, TimeoutException, Address](ServiceOps.fetchAddress(user.addressId))
    } yield (user, address)).value
} 
开发者ID:haghard,项目名称:shapeless-playbook,代码行数:39,代码来源:package.scala

示例2: IndexLogic

//设置package包名称以及导入依赖的类
package com.yannick_cw.elastic_indexer4s.indexing_logic

import akka.NotUsed
import akka.stream.scaladsl.Source
import cats.data.EitherT
import cats.free.Free
import cats.free.Free.liftF
import com.yannick_cw.elastic_indexer4s.Index_results.{IndexError, RunResult, StageSucceeded}

object IndexLogic {
  sealed trait IndexAction[A]
  type FreeIndexAction[A] = Free[IndexAction, A]
  type StageResult = Either[IndexError, StageSucceeded]
  type StageAction[A] = EitherT[FreeIndexAction, IndexError, A]

  case object CreateIndex extends IndexAction[StageResult]
  case class IndexSource[A](source: Source[A, NotUsed]) extends IndexAction[StageResult]
  case class SwitchAlias(minT: Double, maxT: Double, alias: String) extends IndexAction[StageResult]
  case class DeleteOldIndices(keep: Int, aliasProtection: Boolean) extends IndexAction[StageResult]

  // lifts the Algebra into a free context and than into EitherT for easier operations
  private def createIndex: StageAction[StageSucceeded] = EitherT(liftF(CreateIndex): FreeIndexAction[StageResult])
  private def indexSource[A](source: Source[A, NotUsed]): StageAction[StageSucceeded] =
    EitherT(liftF[IndexAction, StageResult](IndexSource(source)): FreeIndexAction[StageResult])
  private def switchAlias(minT: Double, maxT: Double, alias: String): StageAction[StageSucceeded] =
    EitherT(liftF(SwitchAlias(minT, maxT, alias)): FreeIndexAction[StageResult])
  private def deleteOldIndices(keep: Int, aliasProtection: Boolean): StageAction[StageSucceeded] =
    EitherT(liftF(DeleteOldIndices(keep, aliasProtection)): FreeIndexAction[StageResult])

  private def addRunStep(actionDone: StageAction[RunResult], nextStep: StageAction[StageSucceeded]) = for {
    indexResult <- actionDone
    success <- nextStep
      .leftMap(_.copy(succeededStages = indexResult.succeededStages.toList))
  } yield RunResult(indexResult.succeededStages :+ success: _*)

  def write[A](source: Source[A, NotUsed]): StageAction[RunResult] =
    addRunStep(createIndex.map(RunResult(_)), indexSource(source))

  def addSwitch(writeDone: StageAction[RunResult], minT: Double, maxT: Double, alias: String) =
    addRunStep(writeDone, switchAlias(minT, maxT, alias))

  def addDelete(writeDone: StageAction[RunResult], keep: Int, aliasProtection: Boolean) =
    addRunStep(writeDone, deleteOldIndices(keep, aliasProtection))
} 
开发者ID:yannick-cw,项目名称:elastic-indexer4s,代码行数:45,代码来源:IndexLogic.scala

示例3: ClaimAuthController

//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.controllers.security

import javax.inject.{Inject, Singleton}

import cats.data.EitherT
import cats.instances.future._
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import uk.gov.bis.levyApiMock.data._

import scala.concurrent.{ExecutionContext, Future}

@Singleton
class ClaimAuthController @Inject()(scopes: ScopeOps, authIds: AuthRequestOps, clients: ClientOps, timeSource: TimeSource)(implicit ec: ExecutionContext) extends Controller {

  implicit class ErrorSyntax[A](ao: Option[A]) {
    def orError(err: String): Either[String, A] = ao.fold[Either[String, A]](Left(err))(a => Right(a))
  }

  
  def authorize(scopeName: String, clientId: String, redirectUri: String, state: Option[String]) = Action.async {
    implicit request =>
      handleAuth(scopeName, clientId, redirectUri, state)
  }


  private def handleAuth(scopeName: String, clientId: String, redirectUri: String, state: Option[String]) = {
    val authIdOrError = for {
      _ <- EitherT(clients.forId(clientId).map(_.orError("unknown client id")))
      _ <- EitherT(scopes.byName(scopeName).map(_.orError("unknown scope")))
    } yield AuthRequest(scopeName, clientId, redirectUri, state, 0, MongoDate.fromLong(timeSource.currentTimeMillis()))


    authIdOrError.value.flatMap {
      case Left(err) => Future.successful(BadRequest(err))
      case Right(a) => authIds.stash(a).map(id => Redirect(routes.GrantScopeController.show(id)))
    }
  }

  def authorizePost = Action.async { implicit request =>
    case class Params(scopeName: String, clientId: String, redirectUri: String, state: Option[String])
    val m = mapping(
      "scopeName" -> text,
      "clientId" -> text,
      "redirectUrl" -> text,
      "state" -> optional(text)
    )(Params.apply)(Params.unapply)

    Form(m).bindFromRequest().fold(
      errs => Future.successful(BadRequest(errs.toString)),
      params => handleAuth(params.scopeName, params.clientId, params.redirectUri, params.state)
    )
  }
} 
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:56,代码来源:ClaimAuthController.scala

示例4: HTTP

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

import cats.data.EitherT
import cats.{Id, Monad}
import models.store.StoreError
import play.api.Logger
import play.api.mvc.{Request, Result}
import services.booking.{BookingStore, BookingStoreError}

import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}

object HTTP extends APIResults {

  type Task[A] = EitherT[Id, Result, A]

  val unmatchedError: PartialFunction[Error, Result] = {
    case error =>
      Logger.error(s"Unmatched OrientTaskError, responding with Internal Server Error (500): $error")
      JsonInternalServerError("Unknown internal server error", error.toString)
  }

  def ok[A](value: A): Task[A] = EitherT[Id, Result, A](Right(value))

  def fail[A](result: Result): Task[A] = EitherT[Id, Result, A](Left(result))

  def find[A](option: Option[A], error: => Result): Task[A] =
    option match {
      case Some(entity) => ok(entity)
      case None => fail(error)
    }

  def bookingStore[A](task: BookingStore.Task[A]): Task[A] =
    BookingStore.run(task).leftMap(StoreError.http orElse BookingStoreError.http orElse unmatchedError)

  def fromTry[A](t: Try[A], err: Throwable => Result): Task[A] =
    t match {
      case Success(v) => ok(v)
      case Failure(NonFatal(e)) => fail(err(e))
    }

  def run(result: Task[Result]): Result =
    result.fold(identity, identity)
} 
开发者ID:FrancoAra,项目名称:freet-presentation,代码行数:45,代码来源:HTTP.scala

示例5: UserService

//设置package包名称以及导入依赖的类
package net.gutefrage.finch.services

import io.catbird.util._
import cats.data.EitherT
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Request, Response}
import com.twitter.util.Future
import io.circe.parser.parse
import io.circe.generic.auto._
import net.gutefrage.finch.models.User


class UserService {

  private case class RandomUserResults(results: List[User])

  private val hostname = "randomuser.me"
  private val client: Service[Request, Response] =
    Http.client.withTls(hostname).newService(s"$hostname:443")

  def get(): Future[List[User]] = {
    val req = Request("/api/", "results" -> "10")
    req.host = "api.randomuser.me"
    req.contentType = "application/json"
    (for {
      response <- EitherT.right(client(req))
      rawJson <- EitherT
        .fromEither[Future](parse(response.contentString))
        .leftMap(_ => List.empty[User])
      user <- EitherT
        .fromEither[Future](rawJson.as[RandomUserResults])
        .leftMap(_ => List.empty[User])
    } yield user.results).merge
  }

} 
开发者ID:muuki88,项目名称:finch-scalajs-twirl,代码行数:37,代码来源:UserService.scala

示例6: captureFuture

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

import cats.Functor
import cats.data.{ EitherT, Kleisli }
import simulacrum.typeclass

import scala.concurrent.Future
@typeclass
trait CaptureFuture[F[_]] {
  def captureFuture[A](future: => Future[A]): F[A]
}

object CaptureFuture extends CaptureFutureInstances

sealed trait CaptureFutureInstances {
  implicit def futureCaptureFutureInstance[B]: CaptureFuture[Kleisli[Future, B, ?]] =
    new CaptureFuture[Kleisli[Future, B, ?]] {
      override def captureFuture[A](future: => Future[A]): Kleisli[Future, B, A] =
        Kleisli(_ => future)
    }

  implicit def captureFutureEitherT[F[_]: CaptureFuture: Functor, B]
    : CaptureFuture[EitherT[F, B, ?]] =
    new CaptureFuture[EitherT[F, B, ?]] {
      override def captureFuture[A](future: => Future[A]): EitherT[F, B, A] =
        EitherT.right(CaptureFuture[F].captureFuture(future))
    }
} 
开发者ID:notxcain,项目名称:aecor,代码行数:29,代码来源:CaptureFuture.scala

示例7: capture

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

import cats.data.{ EitherT, Kleisli }
import cats.{ Applicative, Functor }
import simulacrum.typeclass

@typeclass
trait Capture[F[_]] {
  def capture[A](a: => A): F[A]
}

object Capture extends CaptureInstances

sealed trait CaptureInstances {
  implicit def kleisliCapture[F[_]: Applicative, B]: Capture[Kleisli[F, B, ?]] =
    new Capture[Kleisli[F, B, ?]] {
      override def capture[A](a: => A): Kleisli[F, B, A] = Kleisli(_ => Applicative[F].pure(a))
    }
  implicit def captureEitherT[F[_]: Capture: Functor, B]: Capture[EitherT[F, B, ?]] =
    new Capture[EitherT[F, B, ?]] {
      override def capture[A](a: => A): EitherT[F, B, A] = EitherT.right(Capture[F].capture(a))
    }
} 
开发者ID:notxcain,项目名称:aecor,代码行数:24,代码来源:Capture.scala

示例8: implicits

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

import akka.http.scaladsl.marshalling.{ Marshaller, ToEntityMarshaller, ToResponseMarshaller }
import akka.http.scaladsl.model.HttpResponse
import cats.data.EitherT
import scala.concurrent.Future

case object implicits {

  implicit def eitherTMarshaller[A](
      implicit ma: ToEntityMarshaller[A],
      me: ToEntityMarshaller[PetClinicError])
    : ToResponseMarshaller[EitherT[Future, PetClinicError, A]] =
    Marshaller(implicit ec =>
      _.value.flatMap {
        case Right(a) => ma.map(me => HttpResponse(entity = me))(a)
        case Left(e) =>
          me.map(
            me =>
              e.httpErrorCode
                .map(
                  code => HttpResponse(status = code, entity = me)
                )
                .getOrElse(HttpResponse(entity = me)))(e)
    })
} 
开发者ID:juanjovazquez,项目名称:scala-petclinic,代码行数:27,代码来源:implicits.scala

示例9: withConnection

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

import cats.data.EitherT
import com.typesafe.config.ConfigFactory
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.{ Failure, Success, Try }
import scala.util.control.NonFatal
import scala.sys.process._
import java.sql.{ Connection, DriverManager }

package object mysql {

  final val Config = ConfigFactory.load()

  final val Ip =
    Try("docker-machine ip".!!).orElse(Try(Config.getString("mysql.ip"))).getOrElse("localhost")
  final val Driver   = "com.mysql.jdbc.Driver"
  final val Url      = s"jdbc:mysql://$Ip/petclinic"
  final val username = Try(Config.getString("mysql.username")).getOrElse("root")
  final val password = Try(Config.getString("mysql.password")).getOrElse("root")

  def withConnection[A](f: Connection => Either[PetClinicError, A])(
      implicit ec: ExecutionContext): Response[A] =
    EitherT(Future {
      var connection: Connection = null
      val comp =
        try {
          connection = DriverManager.getConnection(Url, username, password)
          Success(f(connection))
        } catch {
          case NonFatal(e) => Failure(e)
        } finally {
          if (connection != null && !connection.isClosed)
            connection.close()
        }
      comp.get
    })
} 
开发者ID:juanjovazquez,项目名称:scala-petclinic,代码行数:39,代码来源:package.scala

示例10: dbActionMarshaller

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

import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.marshalling.Marshaller
import akka.http.scaladsl.marshalling.{ ToEntityMarshaller, ToResponseMarshaller }
import cats.data.{ EitherT, State }

trait Marshallers {

  def dbActionMarshaller[S, A](initial: S)(onResponse: S => Unit)(
      implicit ma: ToEntityMarshaller[A],
      me: ToEntityMarshaller[PetClinicError])
    : ToResponseMarshaller[EitherT[State[S, ?], PetClinicError, A]] =
    Marshaller(implicit ec =>
      s => {
        val (s2, r) = s.value.run(initial).value
        onResponse(s2)
        r match {
          case Right(a) =>
            ma.map(me => HttpResponse(entity = me))(a)
          case Left(e) =>
            me.map(
              me =>
                e.httpErrorCode
                  .map(
                    code => HttpResponse(status = code, entity = me)
                  )
                  .getOrElse(HttpResponse(entity = me)))(e)
        }
    })
}

object Marshallers extends Marshallers 
开发者ID:juanjovazquez,项目名称:scala-petclinic,代码行数:34,代码来源:Marshallers.scala

示例11: Main

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

import scala.scalajs.js.JSApp
import scala.util._
import org.scalajs.jquery.jQuery

import cats._
import cats.free._
import cats.implicits._
import cats.data.EitherT

import hammock._
import hammock.free._
import hammock.js.free._
import hammock.circe.implicits._

import io.circe._
import io.circe.generic.auto._

object Main extends JSApp {
  def main(): Unit = {

    import Codec._
    implicit val interpTrans = Interpreter

    case class Resp(json: String)
    case class Data(name: String, number: Int)


    type Target[A] = EitherT[Eval, Throwable, A]
    def Target = EitherT


    val uriFromString: Target[Uri] = Target.fromEither(Uri.fromString("http://httpbin.org/post").leftMap(new Exception(_)))

    val request: Target[Resp] = uriFromString >>= { uri =>
      Hammock
        .request(Method.POST, uri, Map(), Some(Data("name", 4).encode))
        .exec[Target]
        .as[Resp]
    }

    request.value.value match {
      case Right(resp) =>
        val dec = Codec[Data].decode(resp.json)
        jQuery("#result").append(s"""
<h3>Data you sent to the server:</h3>
<pre>$dec</pre>
""")
      case Left(ex) => ex.printStackTrace
    }
  }
} 
开发者ID:pepegar,项目名称:hammock,代码行数:54,代码来源:Main.scala

示例12: Main

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

import cats.Eval
import cats.data.EitherT
import cats.implicits._

import hammock._
import hammock.free._
import hammock.jvm.free._
import hammock.circe.implicits._

import scala.util.{ Failure, Success }

import io.circe._
import io.circe.generic.auto._

object Main extends App {
  import Codec._

  implicit val interpTrans = Interpreter()
  type Target[A] = EitherT[Eval, Throwable, A]
  def Target = EitherT

  case class Resp(data: String)
  case class Data(name: String, number: Int)

  val uriFromString: Target[Uri] = Target.fromEither[Eval](Uri.fromString("http://httpbin.org/post").leftMap(new Exception(_)))

  val request: Target[Resp] = uriFromString >>= { uri =>
    Hammock
      .request(Method.POST, uri, Map(), Some(Data("name", 4).encode))
      .exec[Target]
      .as[Resp]

  }

  request.value.value match {
    case Right(x) => println(s"$x")
    case Left(ex) => ex.printStackTrace
  }
} 
开发者ID:pepegar,项目名称:hammock,代码行数:42,代码来源:Main.scala


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