Created
October 23, 2019 10:14
-
-
Save weiwen99/1e037e9c2bc09aff9a242f0d586040e6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 simple | |
import cats.data.{EitherT, OptionT} | |
import cats.implicits._ | |
import cats.effect._ | |
import io.circe.parser.decode | |
import io.circe.generic.auto._ | |
object SimpleEffect extends IOApp { | |
final case class SimpleData(x: Int) | |
def parseSimpleData(s: String): Either[io.circe.Error, SimpleData] = decode[SimpleData](s) | |
def fetchRawByIdFromDB[F[_]: Effect](id: Int): F[String] = implicitly[Effect[F]].pure(s"""{"x": ${id}}""") | |
def fetchByIdFromDB[F[_]: Effect](id: Int): EitherT[F, io.circe.Error, SimpleData] = { | |
val r1: F[String] = fetchRawByIdFromDB(id) | |
val r2: F[Either[io.circe.Error, SimpleData]] = r1.map(parseSimpleData) | |
EitherT.apply(r2) | |
} | |
sealed trait SimpleError | |
final case class ParsingError(e: io.circe.Error) extends SimpleError | |
case object NotFoundError extends SimpleError | |
def fetchRawByIdFromDB2[F[_]: Effect](id: Int): OptionT[F, String] = id match { | |
case i if (i <= 0) => OptionT.none | |
case i if i <= 100 => OptionT.liftF(implicitly[Effect[F]].pure(s"""{"x": ${id}}""")) | |
case _ => OptionT.liftF(implicitly[Effect[F]].pure(s"""{}""")) | |
} | |
def fetchByIdFromDB2[F[_]: Effect](id: Int): EitherT[F, SimpleError, SimpleData] = | |
for { | |
x <- EitherT.fromOptionF(fetchRawByIdFromDB2(id).value, NotFoundError) | |
y <- EitherT.fromEither[F](parseSimpleData(x).leftMap[SimpleError](ParsingError.apply)) | |
} yield y | |
def run(args: List[String]): IO[ExitCode] = { | |
for { | |
x <- fetchByIdFromDB2[IO](-1).value | |
_ = println(x) | |
y <- fetchByIdFromDB2[IO](100).value | |
_ = println(y) | |
z <- fetchByIdFromDB2[IO](123).value | |
_ = println(z) | |
r <- IO.pure(ExitCode.Success) | |
} yield r | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment