Skip to content

Instantly share code, notes, and snippets.

@woupiestek
Created October 11, 2019 13:59
Show Gist options
  • Save woupiestek/62f22dc8f84d1736fccf1485d62ff4af to your computer and use it in GitHub Desktop.
Save woupiestek/62f22dc8f84d1736fccf1485d62ff4af to your computer and use it in GitHub Desktop.
Cats effect IO query context for phantom dsl.
import cats.effect.{ContextShift, IO, Timer}
import cats.effect.concurrent.Deferred
import com.outworkers.phantom.DefaultImports
import com.outworkers.phantom.Manager.scalaExecutor
import com.outworkers.phantom.builder.query.execution.{FutureMonad, PromiseInterface}
import com.outworkers.phantom.ops.QueryContext
import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.duration._
object phantom {
private implicit lazy val phantomShift: ContextShift[IO] = IO.contextShift(scalaExecutor)
private implicit lazy val timer: Timer[IO] = IO.timer(scalaExecutor)
implicit val ioFutureMonad: FutureMonad[IO] = new FutureMonad[IO] {
override def pure[A](source: A): IO[A] = IO.pure(source)
override def map[A, B](source: IO[A])(f: A => B)(implicit ctx: ExecutionContextExecutor): IO[B] =
source.map(f)
override def flatMap[A, B](source: IO[A])(fn: A => IO[B])(implicit ctx: ExecutionContextExecutor): IO[B] =
source.flatMap(fn)
}
type Promise[T] = Deferred[IO, T]
implicit val ioPromiseInterface: PromiseInterface[Promise, IO] = new PromiseInterface[Promise, IO] {
override def empty[T]: Promise[T] = Deferred.unsafe
override def apply[T](value: T): IO[T] = IO.pure(value)
override def become[T](source: Promise[T], value: IO[T]): Promise[T] = {
value.flatMap(source.complete).unsafeRunAsyncAndForget()
source
}
override def future[T](source: Promise[T]): IO[T] = source.get
override def failed[T](exception: Throwable): IO[T] = IO.raiseError(exception)
}
class IOQueryContext extends QueryContext[Promise, IO, FiniteDuration](10.seconds) {
override def blockAwait[T](f: IO[T], timeout: FiniteDuration): T =
f.timeout(timeout).unsafeRunSync()
}
object catsdsl extends IOQueryContext with DefaultImports
}
@woupiestek
Copy link
Author

import phantom.catsdsl._ instead of com.outworkers.phantom.dsl._ and get cats.effect.IO out of phantom's methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment