Created
April 6, 2017 11:37
-
-
Save abdheshkumar/6072aecef94ac3d7fa9033935391c6c7 to your computer and use it in GitHub Desktop.
UserRepository Example
This file contains 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
import scala.collection.mutable | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.{Await, Future} | |
import scala.concurrent.duration.Duration | |
case class User(id: Long, name: String) | |
@free trait UserRepository[F[_]] { | |
def get(id: Long): FreeS[F, Option[User]] | |
def save(user: Option[User]): FreeS[F, Option[User]] | |
def getAll(filter: String): FreeS[F, List[User]] | |
} | |
implicit val userHandler = new UserRepository.Handler[Future] { | |
val users = mutable.ListBuffer(User(1, "user1"), User(2, "user2"), User(3, "user3")) | |
def get(id: Long): Future[Option[User]] = Future.successful(users.find(_.id == id)) | |
def save(user: Option[User]): Future[Option[User]] = Future { | |
user.foreach { u => users += u } | |
user | |
} | |
def getAll(filter: String): Future[List[User]] = Future.successful(users.find(_.name.contains(filter)).toList) | |
} | |
def program[F[_]](implicit A: UserRepository[F]) = { | |
import A._ | |
for { | |
userInput <- get(12) | |
_ <- save(userInput) | |
users <- getAll("user1") | |
} yield () | |
} | |
val futureValue = program[UserRepository.Op].exec[Future] | |
Await.result(futureValue, Duration.Inf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment