Search

Dark theme | Light theme

January 8, 2016

Ratpacked: Tapping In On A Promise

We can use the wiretap method of the Promise interface to listen in on results. We write an Action implementation which has the result of a Promise encapsulated in a Result object. The wiretap method can be used to do something with a Promise value without interrupting a method chain.

In the following example we tap in on Promise results:

import com.mrhaki.ratpack.Book
import com.mrhaki.ratpack.BookService
import com.mrhaki.ratpack.DefaultBookService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import ratpack.exec.Result
import ratpack.jackson.Jackson

import static ratpack.groovy.Groovy.ratpack

final Logger logger = LoggerFactory.getLogger(ratpack.class)

ratpack {

    bindings {
        bind(BookService, DefaultBookService)
    }

    handlers { BookService bookService ->
         get('book/:isbn') { 
            final String isbn = pathTokens.isbn
            bookService
                    .findBook(isbn)
                    .wiretap { Result<Book> result ->
                        logger.debug 'Book {}', result.value
                    }
                    .map({ Book book ->
                        [author: book.author, title: book.title]
                    })
                    .wiretap({ Result<Map<String, String>> result ->
                        logger.debug 'Book as map {}', result.value
                    })
                    .map(Jackson.&json)
                    .then { bookAsJson -> 
                        render(bookAsJson)
                    }
        }     
    }
}

Written with Ratpack 1.1.1.