Skip to content

Instantly share code, notes, and snippets.

@tjweir
Forked from jrwest/dodelete.scala
Created December 29, 2011 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjweir/1534379 to your computer and use it in GitHub Desktop.
Save tjweir/1534379 to your computer and use it in GitHub Desktop.
Scalaz Functional IO Post Gist Files
val deleteSomeKey: DeleteObject = bucket.delete("some-key")
deleteSomeKey.execute() // actually makes the request to delete the key
def rawFetch(key: String): IO[RiakResponse] = {
val emptyFetchMeta = new FetchMeta.Builder().build() // how this really built is unimportant
rawClient.fetch(name, key, emptyFetchMeta).pure[IO] // 6, rawClient is equivalent to client above
}
def fetch[T](key: String): IO[Validation[Throwable, Option[T]] = {
(rawFetch(key) map {
riakResponseToResult(_) // 7
}) except { t => t.fail.pure[IO] } // 8
}
def riakResponseToResult[T](r: RiakResponse): Validation[Throwable, Option[T]]] = ...
// https://github.com/basho/riak-java-client/blob/master/src/main/java/com/basho/riak/client/operations/FetchObject.java
public T execute() throws UnresolvedConflictException, RiakRetryFailedException, ConversionException {
// fetch, resolve
Callable<RiakResponse> command = new Callable<RiakResponse>() { // 1
public RiakResponse call() throws Exception {
return client.fetch(bucket, key, builder.build()); // setup call via underlying client
}
};
rawResponse = retrier.attempt(command); // 2
final Collection<T> siblings = new ArrayList<T>(rawResponse.numberOfValues()); // 3
for (IRiakObject o : rawResponse) { // 4
siblings.add(converter.toDomain(o));
}
return resolver.resolve(siblings); // 5
}
// remember to import scalaz.effects._
scala> val hiWorld = println("hello, world").pure[IO]
hiWorld: scalaz.effects.IO[Unit] = scalaz.effects.IO$$anon$2@77925ae
scala> hiWorld.unsafePerformIO
hello, world
sealed trait IO[A] {
def unsafePerformIO: A = ...
}
trait RiakOperation[T] {
@throws(classOf[RiakException])
def execute: T
}
//https://github.com/basho/riak-java-client/blob/master/src/main/java/com/basho/riak/client/operations/RiakOperation.java
public interface RiakOperation<T> {
T execute() throws RiakException;
}
def store[T](obj: T): IO[Validation[Throwable, Option[T]]] = {
val emptyStoreMeta = new StoreMeta.Builder().build() // not important how this is really built
val key = // how we get the key from the object is also just an implementation detail
(for {
resp <- rawFetch(key)
fetchRes <- riakResponseToResult(resp).pure[IO] // fetchRes is a Validation[Throwable, Option[T]]
} yield {
fetchRes flatMap {
mbFetched => {
val objToStore = // removing some implementation details here
riakResponseToResult(rawClient.store(objToStore, emptyStoreMeta)) // 9
}
}
}) except { t => t.fail.pure[IO] }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment