Skip to content

Instantly share code, notes, and snippets.

@ValentinTrinque
Created May 22, 2018 14:13
Show Gist options
  • Save ValentinTrinque/76b7a32221884a46e657090b9ee60193 to your computer and use it in GitHub Desktop.
Save ValentinTrinque/76b7a32221884a46e657090b9ee60193 to your computer and use it in GitHub Desktop.
QueryBus pattern implementation - FAILURE
data class GetBookQuery(val page: Int = 1, val limit: Int = 10): Query<BookDto?>
class GetBookQueryHandler: QueryHandler<BookDto?, GetBookQuery> {
override fun handle(query: GetBookQuery): BookDto {
return BookDto("Dune")
}
override fun listenTo(): String = GetBookQuery::class.toString()
}
data class ListBooksQuery(val page: Int = 1, val limit: Int = 10): Query<List<BookDto>>
class ListBooksQueryHandler: QueryHandler<List<BookDto>, ListBooksQuery> {
override fun handle(query: ListBooksQuery): List<BookDto> {
return listOf(BookDto("Dune"), BookDto("Dune II"))
}
override fun listenTo(): String = ListBooksQuery::class.toString()
}
package test
data class BookDto(val name: String)
// Run it!
fun main(args: Array<String>) {
// Initializing query bus
val queryHandlers = listOf(
ListBooksQueryHandler(),
GetBookQueryHandler()
)
val dispatcher = QueryDispatcherMiddleware(queryHandlers)
// Calling query bus
val query = ListBooksQuery()
// Result should be List<BookDto>
val result = dispatcher.dispatch(query)
print(result)
}
interface QueryBusMiddleware {
fun <R, Q : Query<R>> dispatch(query: Q): R
}
class QueryDispatcherMiddleware constructor(handlers: List<QueryHandler< ... , ...>>) : QueryBusMiddleware {
private val handlers = HashMap<String, QueryHandler<..., ...>>()
init {
handlers.forEach { handler -> this.handlers[handler.listenTo()] = handler }
}
override fun <R, Q : Query<R>> dispatch(query: Q): R {
val queryClass = query::class.toString()
val handler = handlers[queryClass] ?: throw Exception("No handler listen to the query: $queryClass")
return handler.handle(query)
}
}
interface Query<R>
interface QueryHandler<R, Q : Query<R>> {
fun handle(query: Q): R
fun listenTo(): String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment