Commit ff6a2d01 by Torkel Ödegaard

Refactored command/query interface

parent 246f41b8
......@@ -9,19 +9,26 @@ import (
type QueryHandler interface{}
type Query interface{}
var (
type Bus interface {
SendQuery(query Query) error
AddQueryHandler(handler QueryHandler)
}
type InProcBus struct {
handlerIndex map[string]QueryHandler
)
}
func InitBus() {
handlerIndex = make(map[string]QueryHandler)
func New() Bus {
bus := &InProcBus{}
bus.handlerIndex = make(map[string]QueryHandler)
return bus
}
func SendQuery(query interface{}) error {
func (b *InProcBus) SendQuery(query Query) error {
var queryName = reflect.TypeOf(query).Elem().Name()
fmt.Printf("sending query for type: %v\n", queryName)
var handler = handlerIndex[queryName]
var handler = b.handlerIndex[queryName]
if handler == nil {
return errors.New("handler not found")
......@@ -38,10 +45,9 @@ func SendQuery(query interface{}) error {
}
}
func AddQueryHandler(handler QueryHandler) {
func (b *InProcBus) AddQueryHandler(handler QueryHandler) {
handlerType := reflect.TypeOf(handler)
queryTypeName := handlerType.In(0).Elem().Name()
fmt.Printf("QueryType %v\n", queryTypeName)
handlerIndex[queryTypeName] = handler
//fmt.Printf("Adding handler for type: %v\n", queryTypeName)
b.handlerIndex[queryTypeName] = handler
}
......@@ -11,13 +11,13 @@ type TestQuery struct {
}
func TestHandlerReturnsError(t *testing.T) {
InitBus()
bus := New()
AddQueryHandler(func(query *TestQuery) error {
bus.AddQueryHandler(func(query *TestQuery) error {
return errors.New("handler error")
})
err := SendQuery(&TestQuery{})
err := bus.SendQuery(&TestQuery{})
if err == nil {
t.Fatal("Send query failed %v", err)
......@@ -27,15 +27,15 @@ func TestHandlerReturnsError(t *testing.T) {
}
func TestHandlerReturn(t *testing.T) {
InitBus()
bus := New()
AddQueryHandler(func(q *TestQuery) error {
bus.AddQueryHandler(func(q *TestQuery) error {
q.Resp = "hello from handler"
return nil
})
query := &TestQuery{}
err := SendQuery(query)
err := bus.SendQuery(query)
if err != nil {
t.Fatal("Send query failed %v", err)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment