Skip to content

Instantly share code, notes, and snippets.

@ubourdon
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save ubourdon/44aa8d0a1744f4dc0185 to your computer and use it in GitHub Desktop.

Select an option

Save ubourdon/44aa8d0a1744f4dc0185 to your computer and use it in GitHub Desktop.
abstract the notion of sycn/async result : solution
import scala.concurrent.Future
trait Repository[ResultWrapper[_], AggregateRoot] {
def create(root: AggregateRoot): ResultWrapper[String]
def retrieve(id: String): ResultWrapper[Option[AggregateRoot]]
def retrieveAll(): ResultWrapper[Set[AggregateRoot]]
def update(root: AggregateRoot): ResultWrapper[ServerResponse]
def delete(root: AggregateRoot): ResultWrapper[ServerResponse]
}
trait ServerResponse
object SyncResultWrapperModule {
type SyncResult[X] = X
}
object AsyncResultWrapperModule { // just a syntaxic sugar to be symetric with type SyncResult
type AsyncResult[X] = Future[X]
}
/**
* https://groups.google.com/forum/#!topic/paris-scala-user-group/VxhUOheC0vQ
* http://www.chuusai.com/2011/06/09/scala-union-types-curry-howard/
* http://rapture.io/exceptions
*/
import org.scalatest.{Matchers, FunSuite}
import usetypes.AsyncResultWrapperModule.AsyncResult
import usetypes.SyncResultWrapperModule.SyncResult
import scala.concurrent.Future
class RepositoryTest extends FunSuite with Matchers {
trait User // a stub aggregate root to simulate repository
test("a sync repository") {
object UserSyncRepository extends Repository[SyncResult, User] {
override def create(root: User): String = "ok"
override def update(root: User): ServerResponse = ???
override def retrieveAll(): Set[User] = ???
override def delete(root: User): ServerResponse = ???
override def retrieve(id: String): Option[User] = ???
}
UserSyncRepository.create(null) shouldBe "ok"
}
test("an async repository") {
import concurrent.ExecutionContext.Implicits.global
import concurrent.Await.result
import concurrent.duration._
object UserAsyncRepository extends Repository[AsyncResult, User] {
override def create(root: User): Future[String] = Future("ok")
override def update(root: User): Future[ServerResponse] = ???
override def retrieveAll(): Future[Set[User]] = ???
override def delete(root: User): Future[ServerResponse] = ???
override def retrieve(id: String): Future[Option[User]] = ???
}
result(UserAsyncRepository.create(null), 1 second) shouldBe "ok"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment