Skip to content

Instantly share code, notes, and snippets.

@pathikrit
Last active February 2, 2016 21:26
Show Gist options
  • Select an option

  • Save pathikrit/5e1ef0bbc620c939a846 to your computer and use it in GitHub Desktop.

Select an option

Save pathikrit/5e1ef0bbc620c939a846 to your computer and use it in GitHub Desktop.
Well typed REST skeleton
object TypedRest {
type Id[A] = Long
object Request {
private[this] trait HasId[A] {
val id: Id[A]
}
trait Get[A] extends HasId[A]
trait Put[A] extends HasId[A]
trait Post[A]
trait Patch[A] extends HasId[A]
trait Delete[A] extends HasId[A]
}
import Request._
trait Repo[A] {
def apply(): Iterable[Get[A]]
def apply(id: Id[A]): Get[A]
def +=(request: Post[A]): Get[A]
def update(request: Put[A]): Get[A]
def update(request: Patch[A]): Get[A]
def -=(request: Delete[A]): Get[A]
}
abstract class CachedRepo[A](cache: Cache[A], repo: Repo[A]) extends Repo[A] {
private[this] def apply(value: Get[A]): Get[A] = {
cache(value.id) = value
value
}
override def apply() = cache.values
override def apply(id: Id[A]) = cache(id)
override def +=(request: Post[A]) = apply(repo += request)
override def update(request: Put[A]) = apply(repo.update(request))
def update(request: Patch[A]) = apply(repo.update(request))
def -=(request: Delete[A]) = {
val result = repo -= request
cache.remove(result.id)
result
}
}
type Cache[A] = Map[Id[A], Get[A]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment