Browse Source

bus: Dispatch now passes empty ctx if handler require it

bergquist 7 years ago
parent
commit
9c1758b593
2 changed files with 21 additions and 10 deletions
  1. 13 3
      pkg/bus/bus.go
  2. 8 7
      pkg/bus/bus_test.go

+ 13 - 3
pkg/bus/bus.go

@@ -96,13 +96,23 @@ func (b *InProcBus) DispatchCtx(ctx context.Context, msg Msg) error {
 func (b *InProcBus) Dispatch(msg Msg) error {
 	var msgName = reflect.TypeOf(msg).Elem().Name()
 
-	var handler = b.handlers[msgName]
+	var handler = b.handlersWithCtx[msgName]
+	withCtx := true
+
+	if handler == nil {
+		withCtx = false
+		handler = b.handlers[msgName]
+	}
+
 	if handler == nil {
 		return ErrHandlerNotFound
 	}
 
-	var params = make([]reflect.Value, 1)
-	params[0] = reflect.ValueOf(msg)
+	var params = []reflect.Value{}
+	if withCtx {
+		params = append(params, reflect.ValueOf(context.Background()))
+	}
+	params = append(params, reflect.ValueOf(msg))
 
 	ret := reflect.ValueOf(handler).Call(params)
 	err := ret[0].Interface()

+ 8 - 7
pkg/bus/bus_test.go

@@ -34,7 +34,6 @@ func TestDispatchCtxCanUseNormalHandlers(t *testing.T) {
 	}
 
 	bus.AddHandler(handler)
-	bus.AddHandlerCtx(handlerWithCtx)
 
 	t.Run("when a normal handler is registered", func(t *testing.T) {
 		bus.Dispatch(&testQuery{})
@@ -42,15 +41,17 @@ func TestDispatchCtxCanUseNormalHandlers(t *testing.T) {
 		if handlerCallCount != 1 {
 			t.Errorf("Expected normal handler to be called 1 time. was called %d", handlerCallCount)
 		}
-	})
 
-	t.Run("when a ctx handler is registered", func(t *testing.T) {
-		bus.DispatchCtx(context.Background(), &testQuery{})
+		t.Run("when a ctx handler is registered", func(t *testing.T) {
+			bus.AddHandlerCtx(handlerWithCtx)
+			bus.Dispatch(&testQuery{})
 
-		if handlerWithCtxCallCount != 1 {
-			t.Errorf("Expected ctx handler to be called 1 time. was called %d", handlerWithCtxCallCount)
-		}
+			if handlerWithCtxCallCount != 1 {
+				t.Errorf("Expected ctx handler to be called 1 time. was called %d", handlerWithCtxCallCount)
+			}
+		})
 	})
+
 }
 
 func TestQueryHandlerReturnsError(t *testing.T) {